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

Josh foo at bar.com
Mon May 20 11:47:25 UTC 2019


On Monday, 20 May 2019 at 11:10:32 UTC, Boqsc 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.
>
> 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?

Normally I would say no, no and no.  Rounding issues will kill 
you every time.  However:

import std.stdio;
import std.range;

void main()
{
	foreach (i; iota(1, 1000)) {
		writefln("%f", cast(float) i / 100.0);
	}
}

Doesn't show any rounding issues, but you still might hit them at 
large values...I just remember back in the day having numbers 
like 0.199999999999999, but maybe that problem has been solved.

What would be safer is to do "fixed point" math, i.e. use an 
integer and when displaying the value convert it to float and 
divide by 100.  So if the user has 50 cents they internal value 
would be 50, if you give them a dollar twenty five (125) then 
they would have 175, and when you go to display it, dividing by 
100 will display 1.75.

As long as you are not multiplying money by money you will be 
fine.  50 cents times 5 is 2.50 (50 * 5 = 250), however 50 cents 
times 50 cents is 2500, which makes no sense but so does 
multiplying money by money...



More information about the Digitalmars-d-learn mailing list