Saturday, September 28, 2019

javascript Addition creates weird decimal issue











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.


Answer



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



No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...