On Thursday, 1 November 2018 at 23:59:26 UTC, kerdemdemir 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)

Anything more precise than the allow precision should truncated.
So in this case 0.00000016123 should turn into 0.00000016.

I coded this which in my tests have no problem :

double NormalizeThePrice( double price, double tickSize)
{
    import std.math : floor;
    double inverseTickSize = 1.0/tickSize;
    return floor(price * inverseTickSize) *  tickSize;
}

writeln(NormalizeThePrice(0.00000016123, 0.00000001));
Returns 1.6e-07 as excepted.

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 ?

Erdemdem

the function you does what you describe is called quantize[1].

However be warned that dealing with money as a floating point type is generally not a great idea. Precision losses (especially when working with ranges like 10^-7) and NaNs (Sociomantic's $9T bug, yes 9T thats what lround(NaN) gives) [2] are thing you _must_ account for.

I _think_ the accepted way of dealing with it is to use an (non overflowing[3]!) integer representing the lowest amount (e.g. 1 cent), and deal in integer multiples of that.

[1]: https://dlang.org/phobos/std_math.html#.quantize
[2]: https://dconf.org/2016/talks/clugston.html
[3]: https://dlang.org/phobos/core_checkedint.html

Reply via email to