2009-11-30 32 views
1

我有一个双(将TaxRate这里),不具有相同值的问题,当它穿越功能:的LINQ to SQL奇怪的漂浮行为

我第一次调用一个函数

DataContext.UpdateCategory(theCategorie.Code, theCategorie.Description, theCategorie.TaxRate, theCategorie.TaxCode); 

当我运行调试器将TaxRate的值是19.6

然后,当我把在dbml的功能的停止点被称为:

[Function(Name="dbo.UpdateCategory")] 
public int UpdateCategory([Parameter(Name="Code", DbType="VarChar(20)")] string code, [Parameter(Name="Description", DbType="NVarChar(512)")] string description, [Parameter(Name="TaxRate", DbType="Float")] System.Nullable<double> taxRate, [Parameter(Name="TaxCode", DbType="NChar(10)")] string taxCode) 
{ 
    IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), uNSPSC, description, taxRate, taxCode); 
    return ((int)(result.ReturnValue)); 
} 

这里的值是19.6000003814697。你看到奇怪的加小数?这两个调用之间没有任何操作,那么为什么会出现这些小数?

+0

1)http://stackoverflow.com/questions/872544/precision-of-floating-point 2)http://stackoverflow.com/questions/1694545/floatin g-point-again 3)http://stackoverflow.com/questions/590822/dealing-with-accuracy-problems-in-floating-point-numbers – KristoferA 2009-11-30 02:04:44

+3

这已被击败致死。阅读每位计算机科学家关于浮点数的知识(http://docs.sun.com/source/806-3568/ncg_goldberg.html),因为您正在处理货币数据并继续前进,所以请更改为十进制类型。 – jason 2009-11-30 02:14:15

+0

是的,但问题来自dbml生成,它不会在存储过程参数(double)和类属性(float)之间使用相同类型(即使两者都是float SqlType) – Gregoire 2009-11-30 02:41:34

回答

1

IsCategorie.TaxRate是浮动的吗?如果是这样,你将分配一个浮点到一个double。额外的小数是由于在双精度较高,所以双的最近一个浮动的19.6 ...

这样做的输出说明它:

float f = 19.6F; 
double d = f; 
double d2 = 19.6D; 

System.Diagnostics.Debug.WriteLine("Float: " + f.ToString()); 
System.Diagnostics.Debug.WriteLine("Double from float: " + d.ToString()); 
System.Diagnostics.Debug.WriteLine("Double: " + d2.ToString()); 

作为一种变通方法,您可以更改为双类型theCategorie.TaxRate的,或者如果你想调用存储过程时,保持它,你可以施放&绕着它的浮动:

DataContext.UpdateCategory(theCategorie.Code, theCategorie.Description, Math.Round((double)theCategorie.TaxRate, 6), theCategorie.TaxCode); 
+0

而我相信C#正在照顾这些问题...... – Gregoire 2009-11-30 02:13:23

+0

感谢您的解决! – Gregoire 2009-11-30 02:23:43

+1

您应该认真考虑将类型更改为小数类型,因为您正在处理货币数字。 – jason 2009-11-30 02:38:16