最近做交易系统,用double或者float处理数据(效率float>double>decimal),当价格经过数据库保存或计算处理时,有精度偏移的概率。比如计算结果为 1.0,实际为0.999998...或1.00001..,这样提交到交易所多半会被拒绝,
于是想出一个函数,目前看没有问题,供大家参考指正
//price是计算价格,price_tick是最小价格波动,例如0.01,相除后取整数,再用decimial和long做精度运算,处理后应该没有精度问题
public static int ChkAccuracy(ref double price, double price_tick) { if (price_tick == 0) { return -1; } long mul = (int)(price / price_tick); if (mul == long.MaxValue || mul == long.MinValue) { return -1; } decimal price2 = mul * (decimal)price_tick; price = (double)price2; return 1; }