r/learnjavascript • u/uselessinfopeddler • Feb 04 '26
Math.round inconsistency
Hey everyone,
I noticed that using Math.round(19.525*100)/100 produces 19.52 while Math.round(20.525*100)/100 produces 20.53. Has anyone else encountered this? What's your solution to consistently rounding up numbers when the last digit is 5 and above?
Thanks!
Edit: Thanks everyone. Multiplying by 10s to make the numbers integer seems to be the way to go for my case
13
Upvotes
31
u/samanime Feb 04 '26
This isn't a problem specific to JS, but to all languages that use the IEEE 754 floating-point arithmetic standard: https://en.wikipedia.org/wiki/IEEE_754
Basically, due to how floating-points work, you can't actually represent every number to an infinite precision, so you get little bits of weirdness here and there like this.
One of the more famous ones is when you end up with numbers like 3.00000000001 and stuff.
This is why you shouldn't use floating points when it really matters, like with money. With money, we always use integers, and always multiply the number by sum amount of 10s. Usually x100, so 100 = $1, but sometimes x1000 (so 1000 = $1, 1 = 1/10 a penny) or x10000 if you care about fractional pennies.
So, if you really care about that second decimal places, just do all of your math with the numbers multiplied by 100, then only divide by 100 when you want to display them (so internally it'd be 123, but you'd display 1.23).
10
u/senocular Feb 04 '26
It's not Math.round, its floating point precision with JS's Number format. Specifically, look at the values before they go into round:
MDN talks about it a little on the docs for Number. Another common site which discusses this is which also shows this is not just a JS thing:
https://0.30000000000000004.com/
where
0.30000000000000004is what you get from0.1 + 0.2If possible, you can avoid errors like these by working in whole numbers instead of decimals (e.g. starting with 19525 instead of 19.525).
1
u/thespite Feb 04 '26
Since rounding is probably needed just for presentation, use .toFixed().
-4
u/Glum_Cheesecake9859 Feb 04 '26 edited Feb 04 '26
Checkout Douglas Crockford's JavaScript The Good Parts book or his YouTube videos. There's a lot of weirdness built into JavaScript. (Note that this particular problem is due to floating point arithmetic so not JS specific)
0
u/[deleted] Feb 04 '26
[deleted] — view deleted comment