1

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?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231
  • 1
    [You should look at the `toFixed()` function.](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed) – Pointy Dec 09 '12 at 14:57
  • possible duplicate of [How to format a float in javascript?](http://stackoverflow.com/questions/661562/how-to-format-a-float-in-javascript) – GSerg Dec 09 '12 at 14:57
  • @GSerg I asked nothing about how to format a float. Read the question before posting about duplicates. – AnchovyLegend Dec 09 '12 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 Dec 09 '12 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 Dec 09 '12 at 15:09

2 Answers2

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);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

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;
}
O'Neill
  • 366
  • 2
  • 5