2

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!

c69
  • 19,951
  • 7
  • 52
  • 82
Daniel Jäger
  • 177
  • 1
  • 3
  • 13
  • Check out this SO question http://stackoverflow.com/questions/744099/javascript-bigdecimal-library – Aviad P. Sep 24 '11 at 16:28
  • possible duplicate of [Javascript calculation bug](http://stackoverflow.com/questions/3138793/javascript-calculation-bug) – Ken White Sep 24 '11 at 16:29
  • Thanks for your answers! Solved with: summe = String(summe.toFixed(2)); summe = summe.replace(".", ","); – Daniel Jäger Sep 24 '11 at 16:36

5 Answers5

6

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.

Community
  • 1
  • 1
duffymo
  • 305,152
  • 44
  • 369
  • 561
3

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.

jbyrd
  • 5,287
  • 7
  • 52
  • 86
2
var val = 49.8 + 199.99;
alert(val.toFixed(2));
fazo
  • 1,807
  • 12
  • 15
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.

Community
  • 1
  • 1
Baz1nga
  • 15,485
  • 3
  • 35
  • 61
0

It can be help for you.

Math.floor(val *10) / 10
Mobile World
  • 126
  • 1
  • 8