Tuesday, 26 December 2017
JavaScript adding decimal numbers issue
Answer
Answer
So I am making a
script that adds two numbers (decimal numbers) together, which I have encountered a
problem.
href="http://jsfiddle.net/DerekL/esqnC/"
rel="noreferrer">http://jsfiddle.net/DerekL/esqnC/
I
made the script, it turns out pretty
good:
0.1 + 0.5
//0.6
0.2 + 0.3
//0.5
But soon I
see:
0.1 + 0.2
//0.30000000000000004
0.01 + 0.06
//0.06999999999999999
And
it does not look right to me. I know it is a shortcoming of using float point with
finite bits, but I can't find a way to fix
that.
Math.ceil
//No
Math.floor //No
.slice
//No
UPDATE
Is
it possible to multiply the numbers by 1000 first, then add them then divide it by
1000?
Answer
Use toFixed
to
convert it to a string with some decimal places shaved off, and then convert it back to
a number.
+(0.1 + 0.2).toFixed(12)
// 0.3
It
looks like IE's toFixed
has some weird behavior, so if you need
to support IE something like this might be
better:
Math.round((0.1 + 0.2) *
1e12) / 1e12
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge micro...
No comments:
Post a Comment