Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliable JS rounding numbers with toFixed(2) of a 3 decimal number

I am simply trying to round up 1.275.toFixed(2) and I was expecting a return of 1.28, rather than 1.27.

Using various calculators and the simple method of rounding to the nearest hundredth, if the last digit is greater than or equal to five, it should round up.

If this doesn't work with toFixed(2), how would it?

People asking whether console.log(1.275.toFixed(2)) prints off 1.28, here's a quick screenshot MacOS Chrome Version 55.0.2883.95 (64-bit)

enter image description here

like image 509
jQuerybeast Avatar asked Feb 08 '17 09:02

jQuerybeast


1 Answers

The 1.275 base 10 number has finite digits but becomes periodic when converted to base 2:

= 0b1.01000110011001100110011001100110011001100110011010
         ^^^^

Since it has infinite digits, it cannot be represented exactly in a computer unless you use an arbitrary precision library (a library than represents numbers as text to keep them in base 10). JavaScript numbers do not use such library for performance reasons.

Since the original value has already lost precision when it reaches JavaScript, rounding it will not improve that.

like image 62
Álvaro González Avatar answered Oct 26 '22 05:10

Álvaro González