In a fully javascript web stack, how can floating point errors be avoided when converting from a currency source in decimal?

68
May 23, 2019, at 05:30 AM

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?

Answer 1

Work in cents and then you get no rounding errors.

READ ALSO
Uncaught (in promise) Error on dispatching action after loading recaptcha value

Uncaught (in promise) Error on dispatching action after loading recaptcha value

I have a contact us page in my reactjs project and i use redux and store for managing states in my form i add react-google-recaptcha componenti have signed up in google recaptcha and all things are fine

52
How can I load a new html page and use an element obtained by onclick of a dynamic object?

How can I load a new html page and use an element obtained by onclick of a dynamic object?

so on my indexhtml page i have dynamic objects created by using appendChild and each one of them has an onclick function

66
How to convert a function into a Pipe Function

How to convert a function into a Pipe Function

I have a function that I am trying to convert into a pipe function but I am still unsure after reading the documentation on angular's website

63
How can I reference object data within an object function?

How can I reference object data within an object function?

I'm trying to make a simple tic tac toe game to learn and practice JavaScript OOP and am having some difficulties

78