-1

In my angular JS application I have three amounts in one object. In Chrome browser debugger i have following:

payment.amountForClosing = payment.amountRemaining - payment.amountReserved;

payment.amountRemaining has a value of 3026.2

payment.amountReserved has a value of 2478.4

after substraction payment.amountForClosing has a value of 547.7999999999997, and 547.8 is displayed. When user tries to make another payment closing, my validation logic returns an error indicating that there is not enough money to make payment closing because of state presented above.

Those amount values come from C# WebApi 2.0 backend, as System.Decimal types.

Erick Boshoff
  • 1,443
  • 2
  • 18
  • 30
vpetrovic
  • 527
  • 4
  • 22

2 Answers2

3

When dealing with currency, worst thing that you can do is use floating point numbers, as you can see. Because of way how floats are stored, some operations may provide incorrect results. Only thing that will always be correct is multiplication/division by power of 10.

Best way is to store currency as Integer/BigInteger, or whatever, and save it with e.g. 4 decimal places so 12100 should represent 1.21

Then you can do subtraction/multiplication of integer numbers and at the end divide by power of 10.

My suggestion is that you transform those numbers to integer before any operation then divide it back to float.

1

Floating point precision in Javascript has been discussed before (eg. here or here). You have the following options:

  1. Convert all your numbers to integers.
  2. Format the result to a fixed number of significant digits using .toFixed(2)
  3. Use a special datatype for decimals like BigDecimal

Out of all of these I agree with @PerunSS that in your case, the best option would be converting the numbers to integers before any operation, and the converting them back.

Community
  • 1
  • 1
snickro
  • 475
  • 4
  • 6