简体   繁体   中英

Javascript: Rounding up to 2 decimal places

I am trying to round a number in Javascript to two decimal places. I consulted the following Stack Overflow post for guidance:

Round to at most 2 decimal places (only if necessary)

Now, in that post, there seems to be two ways to accomplish this. One is toFixed(2) , and the other is Math.round((num + Number.EPSILON) * 100) / 100 , with the latter seeming to be the most accepted way of doing it.

So, given the number 249.025 , this works. Both methods produce 249.03 as expected. However, given the number 294.025 (flip the 4 and the 9 ), both methods fail, and produce 294.02 .

Here is a JSFiddle to demonstrate: https://jsfiddle.net/uj8x4khn/

My question: Is there a rounding method that will work on both of those numbers (and any number)?

Also curious: Why would it work on one number and not a very similar number?

The reason is that 294.025 is not exactly 294.025, but slightly less, because floating point cannot represent that number precisely. You'll notice that when you multiply it with 100, it is even not displayed as 29402.5, but as 29402.499999999999

The best way to solve this, is to go to integer arithmetic only. If you are working with monetary units, calculate everything in cents, not in the currency's main unit. If you are working with 4 decimals, then start out with integers and denote the 4 least significant digits of an integer as referring to the decimal part. Only when you actually want to display it, divide it by the appropriate power of 10. But never store that result for further calculation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM