Removing the precision from double

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Nov 2 00:22:52 UTC 2018


On Thu, Nov 01, 2018 at 11:59:26PM +0000, kerdemdemir via Digitalmars-d-learn wrote:
> I have two numbers
> 
> First The price  = 0.00000016123
> Second Maximum allowed precision = 0.00000001(it can be only 0.001,
> 0.0001, 0.00001, ..., 0.0000000001 bunch of zeros and than a one that
> is it)

Beware!  Floating-point values in D are stored as binary, and certain
decimal fractions cannot be stored exactly in binary.  Because of that,
it's generally better to consider using a decimal arithmetic library for
representing monetary amounts, especially when you have precise
requirements on the number of decimal places a number has to fit into.
IEEE floating-point has some quirks that can give you a nightmare of a
debugging session if you're expecting them to behave exactly like
decimals.


[...]
> I am doing trading and super scared of suprices like mathematical
> errors during the multiplications(or division 1/tickSize) since market
> will reject my orders even if there is a small mistake.
> 
> Is this safe? Or is there a better way of doing that ?
[...]

You probably want to be using a decimal number library instead of
floating-point. The mismatch between the binary representation and the
decimal representation will give you a headache especially if you're
dealing with financial transactions that expects certain behaviours of
the decimal digits, which the binary digits cannot exactly match.

Either that, or store your numbers as fixed-point integers (e.g., as an
int or long with the rightmost n digits interpreted to be the fractional
part -- if you go this route you'd want to encapsulate the arithmetic in
a struct with overloaded operators so that it's more convenient to use,
and you'll want to be careful of arithmetic overflows).

Using IEEE floating-point for financial computations is tricky business,
and you need to fully understand what you're doing and exactly how IEEE
floats work, in order not to get yourself into trouble at some point.


T

-- 
We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare.  Now, thanks to the Internet, we know this is not true. -- Robert Wilensk


More information about the Digitalmars-d-learn mailing list