Pawan Nogariya
Pawan Nogariya

Reputation: 8950

Round upto two decimal places, javascript

I want to round number upto two decimal places in javascript. I have found many posts on SO saying .toFixed method's behavior is unpredictable for different browsers.

And found this solution in many places, that are accepted with no exception

Math.round(yournumber * 100 ) / 100

But I found correct but some wrong results also from this calculation like

Math.round( 1.27532423 * 100 ) / 100  = 1.28 // this seems correct
Math.round( 1.275 * 100 ) / 100       = 1.27 // as I understand it should also 1.28
Math.round( 1.276 * 100 ) / 100       = 1.28 

Am I missing something or my understanding is not correct?

Edit

Just found that

1.275 * 100 is returning 127.49999999999999 and that is the reason, if it returns 127.5, it will yield correct result.

But why it is returning this 127.49999999999999 ????

Upvotes: 1

Views: 2511

Answers (4)

allenhwkim
allenhwkim

Reputation: 27738

To avoid this float number rounding error, I would multiply max precision 10^21 like the following

Math.round(1.275*Math.pow(10,21)/Math.pow(10,19))/100 == 1.28

Upvotes: 0

Arman P.
Arman P.

Reputation: 4394

Here is workaround for that problem:

Math.round((1.275*100).toFixed(2))/100 // returns 1.28

Explanation of the problem can be found in following Q&A

Upvotes: 0

Pawan Nogariya
Pawan Nogariya

Reputation: 8950

As per @scott.korin comment changed

Math.round( 1.27532423 * 100 ) / 100

to

Math.round( 1.27532423 * 10 * 10) / 100 // changed 100 to 10*10 

and it worked like a charm :)

Thanks!

Upvotes: 1

Austin Mullins
Austin Mullins

Reputation: 7427

Floating point math is only precise to the 52nd binary place (which is about the 16th decimal). While 1.275 should round up to 1.28, 1.01000110011b == 1.274902d correctly rounds down to 1.27.

Upvotes: 0

Related Questions