开发者

round in javascript stuck me

hello I want to round an amount in javascript but unable to do and totally stuck. My scenario is, I have a base amount and marukup % on base. On the basis of these two I want to calculate total amount. I have calculated the amount but i want to round the result. I have used following formula

amount=base+((base/100)*markup

This formula always give me result without decimal point. I want to get exact amount upto开发者_开发百科 two decimal points. I have used math.round like this

amount=math.round(base+((base/100)*markup).toFixed(2)

but it always return result without decimal point. For example my base value is 121 and markup is 5%. The amount should be 127.05 . But above formula always returns 127. Any guidelines?


I'm pretty sure math.round returns an integer. Even if you round it then, it'll just be 127.00 anyway.

Here's the correct solution(but it isn't easy):
Do not use non-integer values for money!
It doesn't work.

Use an integer in cents. That is, instead of 127, keep 12700 in your app.
That way all roundings should work fine.


The toFixed(n) function rounds the Number to n decimals, there is no need to use Math.round at all. Try:

total = function (base, markup) { return (base + (base * markup / 100)); }; 
amount = total(121,5).toFixed(2);

Note that amount will be typeof String and not Number.


This should work: amout = (Math.round((base*(1+markup))*100)/100).toFixed(2)

By the way, i was using markup as 5/100...


Sound like a integer division problem to me. I'd guess that javascript is seeing the 100 as an int.

Try this:

amount=(base+((base/100.toFixed(2))*markup).toFixed(2)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜