Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript .toFixed() probem/issue? Reply To: .toFixed() probem/issue?

#171645
kunjan
Participant

how toFixed is working:

So 0.99 = 1
and 0.98 = 1
and 0.97 = 1
and 0.96 = 1
and 0.95 = 1
and 0.94 = 0.9
and 0.93 = 0.9
and 0.92 = 0.9
and 0.91 = 0.9

the reason is:

When you write “0.95” in normal math, the sequence of characters represents exactly the value 95/100. Rounding that will give 1.

When you write “0.95” to represent a 64-bit double precision number, which is what number literals in JavaScript do, the actual value it represents is 0.94999999999999996, which rounds to 0.9 with one decimal digit.

Double numbers are represented by a fixed number of binary digits, which has the consequence that not all decimal values can be represented – just as not all values can be represented by a finite number of decimal digits (e.g., 95/100).

The value 0.94999999999999996 or 0.949999999999999955591079014994 is the closest representable value to 95/100.

solution:

var num = 22.415;
var roundedto = 2;
var n = Math.round(num *Math.pow(10,roundedto))/Math.pow(10,roundedto);
alert(n);

Thanks,
Kunjan