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

Dennis dkorpel at gmail.com
Mon May 20 11:50:57 UTC 2019


On Monday, 20 May 2019 at 11:10:32 UTC, Boqsc wrote:
> I'm frozen in learning basics of D lang since I want to create 
> a simple game and I really would like a clean and simple code,

For a simple game, I think it's the easiest to just store an 
integer of cents (or the lowest amount of currency possible). 
Then storing, adding and comparing just works. Only when you want 
to show it to the user you need some special logic:

```
void printMoney(int cents) {
     writeln("You have $", cents / 100, ".", cents % 100);
}
```

If currency is very prevalent or you like to abstract it, you can 
take a look at dub packages aimed at money/decimal types (or 
write your own if existing libraries don't suit your needs).

http://code.dlang.org/packages/money
http://code.dlang.org/packages/stdxdecimal
http://code.dlang.org/packages/decimal
http://code.dlang.org/packages/fixed


More information about the Digitalmars-d-learn mailing list