Is using floating point type for money/currency a good idea?
kdevel
kdevel at vogtner.de
Mon May 20 19:20:01 UTC 2019
On Monday, 20 May 2019 at 11:47:25 UTC, Josh wrote:
> 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.
Right. Say a chemical is sold at 3165 $/m³. A customer orders
1 ℓ. According to the "round to nearest or even" rule what is the
amount
invoiced (no taxes)? For the non-SI world: 1 m³ = 1000 ℓ.
[...]
> writefln("%f", cast(float) i / 100.0);
[...]
Why cast the integer to float and then device by a double?
writefln("%f", i / 100.);
accomplishes the same with less reading.
Back to the invoice: I would like to promote decimal here:
import std.stdio;
import std.math;
import std.conv;
import decimal;
void calculate (T) ()
{
writefln ("\n%s", T.stringof);
T price_per_m3 = 3165;
T quantity = "0.001".to!T;
T amount = price_per_m3 * quantity;
writefln ("%.2f %.24f", amount, amount);
}
void main ()
{
calculate!decimal32;
calculate!decimal64;
calculate!decimal128;
calculate!float;
calculate!double;
calculate!real;
}
More information about the Digitalmars-d-learn
mailing list