JavaScript adds 0.000000002 to calculation
Source: Pastebin Screenshot: Image
<input alt="Flyer|49.80" type="checkbox" class="price" id="cb3" name="price_3" />
<input alt="CMS|199.99" type="checkbox" class="price" id="cb1" name="price_1" />
Hey folks!
Maybe someone can give me a little hint to the开发者_如何学编程 problem in my source. It adds 0.000000002 to my total sum, when adding 49.8 + 199.99.
Thanks for any suggestions!
You need to understand how floating point numbers work and round your answers to the nearest two digits.
The short answer is that this is how JavaScript, and all languages that use floating point numbers, works. You can't "fix" it. All you can do is accept that floating point numbers aren't exact and deal with it.
Yes, as @duffymo alluded to, the problem has to do with floating point numbers - specifically, the root of the issue (and this is not peculiar to JavaScript) is that there is no way to map 0.1 to a finite binary floating point number.
var val = 49.8 + 199.99;
alert(val.toFixed(2));
The issue is that javascript stores numbers as 64-bit floating point numbers. This means that there are some additions where numbers that would add to 100.00 in decimal math won’t in floating point math. For more refer to the links:
Is floating point math broken?
http://www.scribd.com/doc/5836/What-Every-Computer-Scientist-Should-Know-About-FloatingPoint-Arithmetic
You can avoid this by multiplying all inputs by 100, adding them, then comparing to 10,000. This will work because all integers between 2^-52 and 2^52 can be exactly represented in a double precision floating point numbers, but fractions may not be. http://en.wikipedia.org/wiki/Double_precision_floating-point_format
Another approach is to roll your own decimal addition function to work on number strings.
It can be help for you.
Math.floor(val *10) / 10
精彩评论