admin管理员组文章数量:1323744
I am trying to round to two decimal places in my code below, however, in many cases the Math Round method to control the number of decimal places does not work for me.
var newKitAmount = 1;
var priceNumber = 168;
var updatedTotal = Math.round(priceNumber * newKitAmount*100)/100;
alert("total is : " + updatedTotal); //OUTPUTS 168 instead of 168.00
Output generated:168
Desired output:168.00
Example two:5 * 2 = 10
Desired output:10.00
JS Fiddle
What am I doing wrong? How can I fix it?
I am trying to round to two decimal places in my code below, however, in many cases the Math Round method to control the number of decimal places does not work for me.
var newKitAmount = 1;
var priceNumber = 168;
var updatedTotal = Math.round(priceNumber * newKitAmount*100)/100;
alert("total is : " + updatedTotal); //OUTPUTS 168 instead of 168.00
Output generated:168
Desired output:168.00
Example two:5 * 2 = 10
Desired output:10.00
JS Fiddle
What am I doing wrong? How can I fix it?
Share Improve this question edited Dec 10, 2012 at 7:36 Peter O. 32.9k14 gold badges84 silver badges97 bronze badges asked Dec 9, 2012 at 14:55 AnchovyLegendAnchovyLegend 12.5k41 gold badges152 silver badges240 bronze badges 5-
1
You should look at the
toFixed()
function. – Pointy Commented Dec 9, 2012 at 14:57 - possible duplicate of How to format a float in javascript? – GSerg Commented Dec 9, 2012 at 14:57
- @GSerg I asked nothing about how to format a float. Read the question before posting about duplicates. – AnchovyLegend Commented Dec 9, 2012 at 15:00
- 2 @MHZ This is all about formatting. The rounding works as expected, so your only problem is the proper display, which is formatting. – Olaf Dietsche Commented Dec 9, 2012 at 15:04
- Regardless, posting this is a'duplicate' is wrong, because I asked nothing about floats or formatting, I misunderstood how Math.round is suppose to work. There might be other people out there that expect Math.round() to function as I did, that need to be informed that toFixed() is probably what they're looking for. – AnchovyLegend Commented Dec 9, 2012 at 15:09
2 Answers
Reset to default 9You should use toFixed if you want to get a fixed number of digits after the dot in your string :
var updatedTotal = (priceNumber * newKitAmount).toFixed(2);
you should use a function to round because of the differences between Firefox and Chrome not rounding the same way with toFixed...
function toFixed(a,b){ //where a is the number and b is the number of decimals
var m = Math.pow(10,b);
return Math.round(parseFloat(a)*m)/m;
}
本文标签: javascriptMathround() to control decimal places not workingStack Overflow
版权声明:本文标题:javascript - Math.round() to control decimal places not working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742116563a2421494.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论