If I do 0.3 - 0.2 it gives 0.9999999998 not 0.1 is there a way to make it give a percise decimal? Can't trust a calculator if it's not percise.
Asked
Active
Viewed 97 times
5
-
1Look up floating point numbers, operations and precision. Take a look at this: https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Chris Cousins Aug 23 '18 at 02:48
-
1console.log((a*10-b*10)/10); – sumit Aug 23 '18 at 02:57
2 Answers
1
You could try this solution: https://30secondsofinterviews.org/#what-does-0-1-0-2-0-3-evaluate-to-
A solution to this problem would be to use a function that determines if two numbers are approximately equal by defining an error margin (epsilon) value that the difference between two values should be less than.
const approxEqual = (n1, n2, epsilon = 0.0001) => Math.abs(n1 - n2) < epsilon approxEqual(0.1 + 0.2, 0.3) // true

arkhi
- 488
- 3
- 14
-
what line do i replace? And will this work with all decimals except the random numbers like Pi? Sorry, my friend did a rewrite of the code and i don't know where everything is. – VocalFan Aug 23 '18 at 03:17
-
Actually, based on sunnit’s [previous comment](https://stackoverflow.com/questions/51977668/decimals-are-not-percise/51977817#comment90905378_51977668), you could do this: `const substract = (n1, n2, epsilon = 10) => ( n1 * Math.pow(10, epsilon) - n2 * Math.pow(10, epsilon) ) / Math.pow(10, epsilon);`, then `substract(0.3, 0.2)` – arkhi Aug 23 '18 at 04:38
0
Here is a very quick answer that sums up all of the flags as best I can:
Use, for standard math:
(.3-.2).toFixed(10); //10 can be changed to whatever you like for your string
If you need to do more math with it than do:
Number((.3-.2).toFixed(10));
This last one will give you exactly what you expected in a number type.

David Kamer
- 2,677
- 2
- 19
- 29