I am trying to deal with JavaScript values such as 23.45
, but I want to be able to do mathematical operations on these values (addition, subtraction, multiplication, division) without running into floating point issues. Yes, I might need to round the results sometimes, but I would like it to give reasonable answers.
Consider this in JavaScript:
24.56 * .3
Yields
7.36799999999
I would like it to come out with 7.368
.
Most languages have either a decimal or currency data type to deal with this. Has anyone built a class that can handle this sort of data effectively, or is there any other solution for dealing with these sorts of numbers without having to constantly adjust for floating point errors?
JavaScript has only one type of number. Numbers can be written with or without decimals.
You can use libraries like Decimal. js that will handle your floats as strings. This isn't a bad solution and even comes handy when you have to handle big numbers.
JavaScript supports one mathematical type, 64-bit floating point numbers.
currency. js is a lightweight ~1kb javascript library for working with currency values. It was built to work around floating point issues in javascript. This talk by Bartek Szopka explains in detail why javascript has floating point issues.
Integers.
There is no need to use floating-point for currency. Use fixed-point, where the number of decimal points is 0.
You count in pennies (or possibly in tenths of pennies).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With