Possible Duplicate:
Elegant workaround for JavaScript floating point number problem
Why is it that when adding 2 numbers together using javascript, it will return a crazy number of decimal points?
If I add 285.72 + 142.86 on paper it equals 428.58, you get that same answer with a calculator.
However if I add that number from 2 textboxes it returns 428.58000000000004
Example
I need my javascript to return 428.58. I know I can use .toFixed(), but I'd prefer not to since I don't get why adding two numbers together would create such a crazy number of places after a decimal point.
Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.
This post doesn't get into the details of floating-point arithmetic, but the short of it is most programming languages use a binary floating-point representation which can only approximate many decimal fractions. This results in rounding errors for the most common approaches to rounding in JavaScript.
To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places.
To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.
Not all numbers can be repesented exactly in floating point. Approximations are made and when you have operation after operation on an unexact number the situation gets worse.
See this Wikipedia entry for an example: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
If you changed your addition inputs to something that can be represented exactly by floating point (like 1/8), it would work. Try the numbers: 285.125 and 142.125.
Microsoft .NET has a similar behaviour:
float x = 285.72f
float y = 142.86f
float z = x + y
Results in: z = 428.580017
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