Home › Forums › JavaScript › .toFixed() probem/issue?
- This topic is empty.
-
AuthorPosts
-
March 27, 2012 at 7:28 am #37360
timmey
Memberhey guys,
please check followin code: http://jsfiddle.net/aNCuu/4/
can someone explain why the hell num2 is correct and num1 isn`t (Firefox, Chome)?
and, if you have it, IE 9 shows the correct numbers?
thanx
March 27, 2012 at 9:39 am #100040Mottie
MemberHi Timmey!
Basically the
.toFixed()
rounds off the number. I guess that different browsers handle it differently, so the best solution to just round down would be to just multiply and truncate (demo):var num = new Number(4.725);
var num2 = new Number(4.735);
num = Math.floor( num * 100 ) / 100;
num2 = Math.floor( num2 * 100) / 100;
document.write(num+"
");
document.write(num2+"
");
March 27, 2012 at 10:12 am #100045Senff
ParticipantBut the results of that last demo are not right….
I would expect 4.725 to round off to 4.73, and 4.735 to round off to 4.74.
In the first demo, one is correct and the other one isn’t (I believe that was @timmey ‘s question — why does one round off to the top while the other to the bottom, since both end in 5, in the same browser).
In the second demo, both are incorrect.March 27, 2012 at 9:07 pm #100093Mottie
MemberI believe it is following the rounding up to the nearest even number rule.
March 27, 2012 at 9:15 pm #100094Senff
ParticipantThat makes perfect sense, then! :)
March 28, 2012 at 5:47 am #100107timmey
Memberthx for your response! like senff said, i just wondered why i got differend results.
i found another function that seems to work fine or displays the expected numbers :-) : Your text to link…
June 3, 2014 at 5:01 am #171645kunjan
Participanthow 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.9the 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 -
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.