Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 236
Daniel Jäger Avatar asked Aug 26 '26 08:08

Daniel Jäger


1 Answers

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.

like image 158
duffymo Avatar answered Aug 27 '26 23:08

duffymo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!