最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Math.round() to control decimal places not working - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 9

You 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;
}
发布评论

评论列表(0)

  1. 暂无评论