I used javascripts eval function. But i don't like result. How to fix this problem?
Expression:
eval(1.2+24-25)
result:
0.1999999999999993
I want 0.2 result.
I used javascripts eval function. But i don't like result. How to fix this problem?
Expression:
eval(1.2+24-25)
result:
0.1999999999999993
I want 0.2 result.
The problem you have is that 0.2
, like "most numbers", has no exact representation in IEEE754 and the problem appears as soon as you combine the number in a computation. You'd have a similar problem with 0.2+1-1
.
To get a proper representation, you could reduce to a fixed decimal representation before converting back to a number, for example
var v = +(1.2+24-25).toFixed(10)
This produces
0.2
The general practice is to do all computations with numbers without rounding or using toFixed
and only use this kind of transformation when presenting the result to the user (then the +
isn't really useful).
First off, there's no reason at all for eval
here. Just:
1.2 + 24 - 25
will do what you want.
The issue here is that the IEEE-754 double-precision floating point numbers used by JavaScript (and other languages) are not perfectly accurate. They're very fast, but not perfectly accurate.
The more famous example is:
0.1 + 0.2
...which gives you 0.30000000000000004
.
If you're doing financial calculations or similar where you need the results to be the same as you'd get working with pencil and paper, you'll want a library that does that style of thing (which will be slower, but rather than having the issues like the above, will have the issues you're more familiar with, like not being able to represent 1 / 3
with complete accuracy). This question and its answers here on Stack Overflow discuss various library options.
use toFixed function
var num =1.2+24-25;
var fixed=num.toFixed(1);
fixed is now "0.2" as a string