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

H. S. Teoh hsteoh at quickfur.ath.cx
Mon May 20 20:50:24 UTC 2019


On Mon, May 20, 2019 at 11:10:32AM +0000, Boqsc via Digitalmars-d-learn wrote:
> https://dlang.org/spec/float.html
> 
> 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, however
> to me floating points are magic.

Read this:

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html


> https://wiki.dlang.org/Review_Queue
> Since std.decimal is still work in progress and apparently its
> development is stuck for a while, should I just somehow use floating
> point to store currency or wait until Decimal package will be finally
> included into std Phobos of D lang?

You do *not* want to use floating-point for money/currency (unless your
currency is in base 2). This is because certain decimal fractions cannot
be represented exactly in binary, and sooner or later you will run into
unexpected roundoff errors.

Just use a plain old integer with a fixed decimal point. I.e., 10.25 is
represented as 1025 with an implicit division by 100.  I wouldn't even
bother with BigInt unless you expect to be dealing with sub-cent money
amounts or extremely large amounts of money. BigInt allows arbitrary
precision, but at the cost of slower operations. For a game, it's
overkill. Just use int (or long) with fixed-point operations.


T

-- 
PNP = Plug 'N' Pray


More information about the Digitalmars-d-learn mailing list