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

57
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?

Work in cents and then you get no rounding errors.

POPULAR ONLINE

44

### 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

59

### 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

56

### 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

60