I had to design a money-handling application recently that was fully in javascript, express.js, REST apis, the full node/browser js stack. Unfortunately, the application dealt with a variety of custom calculations like averaging out the results. Of course, when averaging results, floating point addition and division comes into play. Thus, I would get values that were off by about 0.12 (12 cents!).
I understand the recommended options for dealing with floats in theory:
- Calculate in integers
- Round
- Use a decimal datatype somewhere else
The integers-for-currency approach is fine, that would make sense, but unfortunately if requests are coming in in decimal form, then some kind of calculation to initially convert floats to integers still has to happen, and the potential for error is still retained.
So let's say a request comes in to add 44.67
to a list of dollar values.
It'd be nice to work with it in clean integer units, but to get there requires multiplying by 100 first, which I am suspicious causes the whole set of errors to come with it.
So in javascript what is the process for handling smooth conversion between decimal or dollar requests and calculations that avoid floating point errors?
In that case is a database required, and the values just have to be passed in to the database as strings? Or is there a way to convert "losslessly" to integers within the javascript? Or is there some other technique when handling money and requiring exactness?