I'm working in map app. So I manipulate a lot of with float number (lat and long). I knew that we have issue related to 0.1 + 0.2 !== 0.3. So how I can void it? Is there any method to add multiple float number?
Asked
Active
Viewed 1,338 times
1
-
2Do you *really* have an issue, or do you want to feel warm, fuzzy, and clever inside? (It's really not often a problem.) In any case, this requires using a *fixed precision* library (or other manual handling). – user2864740 Feb 20 '14 at 04:50
-
1Introduce some `var epsilon = 0.0001` and check that `Math.abs()` of a difference between 2 operands is less than it. – zerkms Feb 20 '14 at 04:50
-
@user2864740: do you really that lazy to run `0.1 + 0.2 != 0.3` or just wanted to post something "smart"? – zerkms Feb 20 '14 at 04:51
-
@zerkms I'm saying *it likely doesn't matter*; it's only an "issue" if dealt with incorrectly (which depends upon context). I have not seen the "issue" discussed in this question (it merely points out a widely understood effect of base2 floating-point implementations), which is what my previous comment - as snarky as it may seem - attempted to draw out. – user2864740 Feb 20 '14 at 04:51
-
@user2864740 I want to feel ok when working with float number. – Eddy Feb 20 '14 at 04:54
-
1@Eddy Except when needing to deal with *exact* precision values, such as is the case of money (and some other problems), relative precision floating point is generally precise enough, easy/standard, and [relatively] fast. Perhaps the comparison methods used could be revised to take in an epsilon instead of a direct equality? That is, it's not that "the math is broken", so much that "the use of == is often inappropriate". Can you make a point - e.g. an "issue" - in the main post arguing for one way or the other? – user2864740 Feb 20 '14 at 04:55
2 Answers
2
One solution is to compare values in a way that takes account of the (extremely small) loss of precision caused by IEEE 754 floats not being able to accurately represent all fractions, e.g.
function diff(a, b) {
return Math.abs(a - b);
}
var a = 0.1;
var b = 0.2;
if ( diff(0.3, a+b) > 1e-10) {
/* fail */
}

Mark Dickinson
- 29,088
- 9
- 83
- 120

RobG
- 142,382
- 31
- 172
- 209
0
If you need precision in Javascript, you should use Big Numbers like https://github.com/MikeMcl/big.js/

Silviu Burcea
- 5,103
- 1
- 29
- 43