I need to calculate price of shipping every 500g. I need it in Javascript or PHP. Please help me out figure it. For Eg: Lets take the base price of Rs 40 and the Base weight as 500g. So if I enter 250g it should say 40 and If I enter 850g then it should say Rs 80 and it goes on like that.
Advertisement
Answer
You can calculate the price with:
ceil(weight / baseWeight) * basePrice
In your first example:
ceil(250 / 500) * 40 = ceil(0.5) * 40 = 1 * 40 = 40
In your second example:
ceil(850 / 500) * 40 = ceil(1.7) * 40 = 2 * 40 = 80
ceil
is a common function in most programming languages: PHP, JavaScript
Be aware of integer division in some programming languages and make sure that 250 / 500
returns 0.5
and not 0
.
Also rounding errors can occur.