This question wasn't asked on stackoverlow yet! I'm not asking why 0.1+0.2 doesn't equal 0.3, I'm asking very different thing! Please read the question before marking it as a duplicate.
I've written this function that shows how JavaScript stores float numbers in 64 bits:
function to64bitFloat(number) {
var f = new Float64Array(1);
f[0] = number;
var view = new Uint8Array(f.buffer);
var i, result = "";
for (i = view.length - 1; i >= 0; i--) {
var bits = view[i].toString(2);
if (bits.length < 8) {
bits = new Array(8 - bits.length).fill('0').join("") + bits;
}
result += bits;
}
return result;
}
Now I want to check if the result of 0.1+0.2
is actually stored as it's shown in the console 0.30000000000000004
. So I do the following:
var r = 0.1+0.2;
to64bitFloat(r);
The resulting number is:
0 01111111101 0011001100110011001100110011001100110011001100110100
Now, let's convert it to the binary:
Calculated exponent:
01111111101 = 1021
1021 - 1023 = -2
Get it all together,
1.0011001100110011001100110011001100110011001100110100 x 2 ** -2 =
0.010011001100110011001100110011001100110011001100110100
Now, if we convert the resulting number into decimal using this converter, we get:
0.3000000000000000444089209850062616169452667236328125
Why doesn't console show the whole number, instead of just it's more significand digits?
Conclusion. I was super surprised to learn that 0.1 + 0.2 is actually supposed to equal 0.30000000000000004 in JavaScript because of floating point math.
The console. log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.
console. log will log to the console (as the name suggests) while return just ends the function and passes the value to whatever called that function. Since you're not using that return value, you won't see anything but it is produced.
This is happening because your form is submitting to itself and the page loads in a fraction of seconds for you to notice the difference.
The console.log method is non-standard. In Firefox, you can specify the number of decimal with a format specifier
console.log('%.60f', 0.1 + 0.2)
gives
0.300000000000000044408920985006261616945266723632812500000000
Which is the same number as the one given by your converter.
Note that, this doesn't work in chrome.
In conclusion:
Actually you don't have to write such a long question. What you could do is just open console and type:
var a = 0.3000000000000000444089209850062616169452667236328125;
console.log(a);
that would still give you result - 0.30000000000000004 (at least in Google chrome console).
And the reason why it is like that, is because limitations of JS, which only allow to show 16 chars of a float. You can read more in answer to this question: https://stackoverflow.com/a/19613321/3014041
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With