Is using floating point type for money/currency a good idea?

Era Scarecrow rtcvb32 at yahoo.com
Mon May 20 15:07:35 UTC 2019


On Monday, 20 May 2019 at 11:50:57 UTC, Dennis wrote:
> For a simple game, I think it's the easiest to just store an 
> integer of cents (or the lowest amount of currency possible).

  Back in 2003 i did this very thing for when creating my C 
program for suggesting and helping with credit card payments, so 
it could make suggestions of which ones to pay off in what 
amounts, as i found using float to be too unreliable.


Another option could be to use floats to a very limited state, 
say after calculations (cay calculating interest) you could 
convert to an int then back to float. (money = cast(float) 
(cast(int)money*100) /100)) to get as clean/close to the proper 
value as you can. (Though you may still end up off by a fraction 
of a penny).

Josh's suggestion is close:

      writefln("%f", cast(float) i / 100.0);

The format should be "%f.2", which should do fine for your 
purposes as it would round to the correct value (unless you're 
working with numbers over say 16Million, then float will start 
giving issues, and doubles might be needed).


A third option could be to make your own type, a fixed precision 
int, which would be a struct that you determine precision by some 
arbitrary means (bits, digits, etc) and then do your tostring 
method to handle output appropriately. Not the best, but it would 
also work.

I suppose the last method would be to make a BCD (Binary Coded 
Decimal) type. This is used in calculators (and 8bit BASIC) where 
it's a 6 byte value where every nibble (4bits) is a digit. The 
first byte is the exponent (+/- 128) and 5 bytes store 10 digits 
of data allowing VERY precise values. But the overhead and setup 
seems a bit impractical outside of emulation.


The easiest i would think is just consider the currency a whole 
number, and if you are working with fractions, only do the 
conversion when printing/outputting.


More information about the Digitalmars-d-learn mailing list