Answer the question
In order to leave comments, you need to log in
Do you get many decimal places when adding in JavaScript?
I do in the JavaScript console Opera Dragonfly:
>>> 31.01 + 1
32.0100000000005
>>> 31.02 + 1
32.0199999999996
>>> 31.03 + 1
32.03
Variations with ParseFloat / Parseint did not led to anything, from where it takes 0.0000000000005 in the first case and where 0.000000000000004 in the second?
Answer the question
In order to leave comments, you need to log in
Most likely a feature of floating point numbers.
The fact is that when coding some numbers, the binary code turns out to be infinite. For example, 0.1 in binary is 0.0(0011). In computer memory, this will be 1.1001100110011001100110011001100110011001100110011010b * 2^(-4), and when converted to decimal, it will be 0.10000000000000000555111512.
IMHO this is one of the problems with dynamic typing.
stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem
This is nonsense :) IEEE double tricks:
Read en.wikipedia.org/wiki/Double_precision_floating-point_format
If precision is needed, calculate with a fixed point ((31.01 100 + 1 100)÷100). Don't like the view, use toFixed.
>>> 9007199254740992
9007199254740992
>>> 9007199254740993
9007199254740992
>>> 9007199254740994
9007199254740994
>>> 9007199254740995
9007199254740996
In fact, here are inaccurate calculations . There is why and how to fight, although here in general they have already been answered. But this is like a proof, since the site is quite authoritative.
By the way, I started learning javascript from this tutorial. Immediately in my head, of course, it will not fit, but during the writing of the code it will pop up and save me from such children's mistakes.
var t = 2.32356121212;
function fixed(N, n) {
return Math.round(t * Math.pow(10, n))/Math.pow(10, n);
}
fixed(t, 4);
Conclusion:
2.3236
If you are not afraid of "terrible" performance losses from converting to strings, there is such a hack:
function (num) {
var a=num%1;
var b=Math.pow(10,num.toString().split('.')[1].length);
return Math.round(a*b)/b;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question