In php, we have number_format(). Passing it a value such as:
number_format(3.00 * 0.175, 2);
returns 0.53, which is what I would expect.
However, in JavaScript using toFixed()
var num = 3.00 * 0.175;
num.toFixed(2);
returns 0.52.
Ok, so perhaps toFixed is not what I want… Maybe something like this…
var num = 3.17 * 0.175;
var dec = 2;
Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
No, that doesn’t work either. It will return 0.56.
How can I get a number_format function in JavaScript that doesn’t give an incorrect answer?
Actually I did find an implementation of number_format for js, http://phpjs.org/functions/number_format, but it suffers from the same problem.
What is going on here with JavaScript rounding up? What am I missing?
JavaScript does badly with floating point numbers (as do many other languages).
When I run
In my browser, I get
Which will not round up to 0.525 with
Math.round. To circumvent this, you kind of have to multiply both sides until you get them to be integers (relatively easy, knowing some tricks help though).So to do this we can say something like this:
This may look kind of funky, but here’s some pseudo-code:
Hope this is what you are looking for. Here’s a sample run: