繁体   English   中英

linq to sql奇怪的浮动行为

[英]linq to sql strange float behaviour

我有一个双精度问题(这里是TaxRate),当它通过函数传递时没有相同的值:

我先调用一个函数

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 您看到奇怪的加了十进制吗? 这两个调用之间没有任何操作,那么为什么出现这些小数?

TheCategorie.TaxRate是否为浮点数? 如果是这样,则将浮点数分配为双精度数。 多余的小数部分是由于双精度较高,因此双精度最接近浮点数的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的类型更改为double,或者如果要将其保留为float,则可以在调用存储的proc时对其进行强制转换和四舍五入:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM