0

Ive read about typescript number type is floating point and may result in errors when used in financial programs where numbers are represented to two decimal places. I realize I can use longs are represent everything in cents, but its tedious to do currency multiplication because $1.00 x $1.00 = $10.00 for example unless you remember to divide by 10^(n*2) where n is the number of currency factors.

I was thinking I could maybe just use something like:

let result = [some floating math with dollar amounts]
let answer1 = Math.round(result * 100) / 100;

For my application which is dealing in $ amounts not to exceed say $100MM, it seems like it will suffice to errors like $2.00 x 20% x 10% != $0.04 but I'm not sure this will work in all the cases that might produce similar errors when I am doing a lot of math on currency amounts in my application.

isherwood
  • 58,414
  • 16
  • 114
  • 157
GGizmos
  • 3,443
  • 4
  • 27
  • 72
  • 6
    When does it ever make sense to multiply currency values together? What is a dollar^2? – Mark Reed Apr 14 '20 at 20:29
  • 2
    Related https://stackoverflow.com/q/3730019/8186898 – Nino Filiu Apr 14 '20 at 20:34
  • I understand the theoretical issue, but have been unable to find a realistic example where Math.round(result*100)/100 yields an answer off by more then $0.01. Seems a lot easier than dealing with BigInts – GGizmos Apr 14 '20 at 21:03
  • Mark Reed: In my case it came up in exchange rates if its stored in the DB as say, US$ per Swedish KR (about $0.10) So if you store those as integer pennies, and you want to convert, say KR150 you get '10' x '150000' . – GGizmos Apr 14 '20 at 21:35
  • 2
    Assumptions like your "For my application which is dealing in $ amounts not to exceed say $100MM" have broken financial software in the real world, for example during the Zimbabwe currency crisis, where hyperinflation peaked at a staggering 80000000000% per month. The amounts for even simple transactions became so high that it broke the datatypes used in the software. Just don't do it. Money is not a float, it is not an integer, it is money. The correct datatype to store money is `Money`. If your language's standard library doesn't have it (most don't), you need to write it. – Jörg W Mittag Apr 14 '20 at 21:46
  • "Just don't do it" sounds more like a religious conviction than an actual answer to my question. I have a zimbabwe $10 Trillion note hanging on my wall. I can also decide for myself the risks associated with hyperinflation on my app versus the effort and potential introduction of errors from engineering a new "money class". None of it is really an answer to the question I posed. – GGizmos Apr 29 '20 at 00:53

0 Answers0