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?
ku4jQuery-kernel contains both a money class and a math utility that contain operations and rounding, including round, roundUp and roundDown. These are nice methods because you can pass a value to round to. For example you can do $.math.round(3.4567, -2) and it will round the number 3.4567 to the nearest 10^-2. The same goes for money. $.money(100.87).divide(2).roundUp().toString() will yield "$50.44". You can go further and add the denomination of money as a second parameter, say "B" for Bitcoin, $.money(100.87, "B").divide(2).roundUp().toString(). You can find more about this library here ku4jQuery-kernel and more libraries that you may find useful here kodmunki github. These libraries are closely maintained and used in many production projects. If you decide to try them, I hope that you find them useful! Happy coding :{)}