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

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Mon May 20 14:34:53 UTC 2019


On Monday, 20 May 2019 at 12:50:29 UTC, Simen Kjærås wrote:
> There are some caveats when using doubles, as floating-point 
> math is not always equal to regular math. For instance, if you 
> had the entire world economy in one variable, you could 
> subtract a cent at a time without the variable decreasing. If 
> these cents were simultaneously added to a different variable 
> (to represent a transaction), this would be an infinite source 
> of money.

Yes, but it is fine until  2^53 which is the number 
9007199254740992.  So better than 31 bit ints and only slightly 
worse than 63 bit (signed).

Doubles behave like like integers from 0 up to 2^53 for addition, 
so if you do cents in double then you also get accurate 
representation of cents while also getting decent fractional 
representation when converting to another currency.

If it is important for the game to not leak resources then I 
guess you would have to recalibrate the system from time to time. 
It might be hard to find where money leak. Integers have the same 
problem, however.


If it is a game, you might want to use the same storage-type and 
system for all countable resources, though. Then you could do 
something more advanced and memory efficient, either one storage 
object per owner, or as a global database object.

So if you have lots of (unlimited) resource-pools (accounts, 
bottles, containers etc) to track you could to create your own 
"bank" or "wallet" as an in-memory database which uses variable 
length data records with encapsulated memory management on a 
local heap. So if you have 200 units it uses 1 byte more than an 
empty account, if you have a billion units it uses 4 bytes, a 
trillion units uses 5 bytes, 1000 trillion units use 7 bytes more…

One advantage of using a "bank" is that you can ensure that 
resources don't leak as you have to set up a "transaction" 
between "accounts". (the same amount of money/resources are both 
added or removed  at single point). Less error-prone.

If it is a simulation game then it would also be easier to create 
logs that are useful for debugging/balancing if you have a 
mandatory "transaction" concept (you get a single point where all 
a transactions have to pass, and there you can log it).


Anyway, lots of options. Have fun!



More information about the Digitalmars-d-learn mailing list