3

Is it safe to use JavaScript number type (64-bit double precision) for money operations? We plan to develop a software for small businesses and amounts are usually less than 100.000$, but I think numbers may be much larger because we use local currencies and for example, 1$ = 6.5 Chinese yuan.

I know that there may be lost of precision, but how bad is it in the real world?

I also suggest that we can skip problems like

0.2 + 0.1 = 0.30000000000000004

because after truncating the number using local currency settings it would be the same eg $0.30

Some people also recommend to scale values by multiplying them by 100, but I'm not sure this will work in every situation, because I suggest there may be currencies with more than 2 digits after point.

KBS
  • 69
  • 5

2 Answers2

4

I would suggest you to use Integers when you are dealing with money. Floating point arithmetic is broken and is unreliable so its better to use fixed type for money calculations.

However there are bignumber.js library which is often used to deal with calculations related to money.

Here is a good reference and related thread on the same: Precise Financial Calculation in JavaScript. What Are the Gotchas?

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

I think that the best way is using the special libraries

like the bignumber.js

For example:

0.3 - 0.1                           // 0.19999999999999998  
x = new BigNumber(0.3)
x.minus(0.1)                        // "0.2"
x                                   // "0.3"
Alexey Sh.
  • 1,734
  • 2
  • 22
  • 34