凡在本C#中的财务计算的浮点问题? [英] Where is the floating point problem in this C# financial calculation?

查看:223
本文介绍了凡在本C#中的财务计算的浮点问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一条FIX消息的交易分配,在价格给出的美分的(ZAR / 100),但佣金给出的兰特的。这些值再由常数psented $ P $。当我运行这个计算, commPerc1 显示0.099999999999999978一个值, commPerc2 显示0.1。这些值看起来由X10不同,但与计算返回的支票的兰特的,无论是 commRands1 commRands2 显示的分别为336.4831554和336.48315540000004非常相似的价值观。

I receive a FIX message for a trade Allocation, where Price is given in cents (ZAR / 100), but commission is given in Rands. These values are represented by the constants. When I run this calculation, commPerc1 shows a value of 0.099999999999999978, and commPerc2 shows 0.1. These values look to differ by x10, yet with the check of calculating back to Rands, both commRands1 and commRands2 show very similar values of 336.4831554 and 336.48315540000004 respectively.

private const double Price = 5708.91;
private const double Qty = 5894;
private const double AbsComm = 336.4831554;

static void Main()
{

    double commCents = AbsComm * 100;
    double commPerc1 = commCents / (Qty * Price) * 100;
    double commRands1 = (Qty * Price) * (commPerc1 / 100) / 100;

    double commPerc2 = (AbsComm / (Qty * (Price / 100))) * 100;
    double commRands2 = (Qty * Price) * (commPerc2 / 100) / 100;
}

请注意: 我处理遗留code在这些地方转换为十进制会涉及一些变化和质量保证,所以现在我必须接受

PLEASE NOTE: I am dealing with legacy code here where a conversion to decimal would involve several changes and QA, so right now I have to accept double.

推荐答案

不要使用的财务计算,使用十进制代替。浮点数是物理,测量值,其中值永远不会确切反正确定。但是,对于金融计算你正在使用的确切的值,你不能失误,由于浮点再presentations。这就是十进制制成的:

Don't use double for financial calculations, use decimal instead. Floating point numbers are OK for physical, measured values, where the value is never exact anyway. But for financial calculations you're working with exact values, you can't afford errors due to floating point representations. That's what decimal is made for:

十进制值类型是适当的财务计算,需要大量的显著整数和小数位,没有舍入误差。

The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors.

(从MSDN)

这篇关于凡在本C#中的财务计算的浮点问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆