March 27, 2012 at 7:28 am #37360
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?
thanxMarch 27, 2012 at 9:39 am #100040
.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;
March 27, 2012 at 10:12 am #100045
But 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 #100093March 27, 2012 at 9:15 pm #100094
That makes perfect sense, then! :)March 28, 2012 at 5:47 am #100107
thx 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 #171645
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.
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.
var num = 22.415;
var roundedto = 2;
var n = Math.round(num *Math.pow(10,roundedto))/Math.pow(10,roundedto);
You must be logged in to reply to this topic.