I’m creating a budget application with javascript. I have to let javascript do most of the operations. So I have some controls where the user changes the desired amount for a category and my application shows the new amounts for the subcategories.
So If I have
+ Auto $50.23
– Gas $30.25
– Maintenance $6.27
– Insurance $10.02
– …
So if the user changes Auto 50.23 to 90.00, the amounts for Gas, Maintenance, Insurance, etc would reflect the % increase in their parent category.
The problem is that after a few operations I loose precision and it creates some nasty bugs. Most of the times the numbers don’t add up (as they should). After changing the amount for auto a few times and then set it to 0, the other amounts don’t always go to 0, and sometimes they go below 0 giving me a NaN, so if I later change Auto for something greater than 0, my NaN will stay NaN.
I just heard somebody say that fractions in javascript are approximations which is another problem. I tried to google to see if this is a fact, but couldn’t find anything (maybe I didn’t look for the right terms)
I’m sure some of you have ran into similar problems, what would you suggest?
Somebody suggested to multiply my original number by 100 and then do all operations, but I’m afraid that this won’t help me get away with the problem of loosing precision.
Any ideas?
I will appreciate your help!
Binary floating-point numbers are inept at handling decimal fractions, so 0.1 + 0.2 is not equal to 0.3. This is
the most frequently reported bug in JavaScript, and it is an intentional consequence of having adopted the
IEEE Standard for Binary Floating-Point Arithmetic (IEEE 754). This standard is well-suited for many
applications, but it violates most of the things you learned about numbers in middle school. Fortunately,
integer arithmetic in floating point is exact, so decimal representation errors can be avoided by scaling.
For example, dollar values can be converted to whole cents values by multiplying them by 100. The cents then
can be accurately added. The sum can be divided by 100 to convert back into dollars. People have a
reasonable expectation when they count money that the results will be exact.
“JavaScript: The Good Parts by Douglas Crockford. Copyright 2008 Yahoo! Inc.,
978-0-596-51774-8.”