2

I'm writing an app for myself. I need to handle money and currencies.

I read this and I want to try the second approach:

You can multiply floats into integers before you calculate, then divide them back.

(0.2 * 100 + 0.01 * 100) / 100 // returns 0.21

It’s a fine solution but requires extra calculations either on object construction or on each manipulation. This isn’t necessarily draining on performances, but still more process work than necessary.

With my backend I store values in int64.

QUESTION

Let's take 1.1.

1.1 * 100 = 110.00000000000001!!!

How can I be safe for all operations?

It's safe to always use (1.1 * 100).toFixed()?

Community
  • 1
  • 1
Fred Hors
  • 3,258
  • 3
  • 25
  • 71
  • 1
    *"How can I be safe for all operations?"* don't deal with the actual currency, always store and do math with it's smallest denomination. For example cents over dollars. And only when you need to render the amount convert/format it to what your customers expect to see (dollars, not cents). That way you get rid of all the floating point math and you don't have to convert back and forth all the time. – Thomas May 09 '20 at 12:15
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – jonrsharpe May 09 '20 at 12:16
  • 1
    `toFixed` returns a string. If you need an integer, use `Math.round(1.1 * 100)`. As long as you are multiplying by 100 there should be no issues. – GOTO 0 May 09 '20 at 12:35
  • @Thomas, this not answer my question. I know I can use cents (smallest denomination). I'm asking something else. – Fred Hors May 09 '20 at 12:50
  • @jonrsharpe it's a different question. – Fred Hors May 09 '20 at 12:50
  • @GOTO 0 you'are right! Thanks! – Fred Hors May 09 '20 at 12:50
  • @Thomas: Using integers with the smallest denomination does not solve all problems. Neither integers, decimal fixed-point, binary fixed-point, decimal floating-point, nor binary floating-point can represent the unit price of items sold three for a dollar. Nor can they compute interest without exceeding available precision after a few compoundings (often just one term). There is no format that magically solves these problems; the only solution is for the programmer to know what they are doing. – Eric Postpischil May 09 '20 at 14:49
  • https://currency.js.org/ this can relief or, using bigint and storing values 100times bigger to store cents https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt – nerkn Oct 04 '21 at 15:08

0 Answers0