代码之家  ›  专栏  ›  技术社区  ›  Gregoire

linq到sql奇怪的浮点行为

  •  1
  • Gregoire  · 技术社区  · 15 年前

    我首先调用一个函数

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

    当我运行调试器时,TaxRate的值是

    然后,当我在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 . 你看到那个奇怪的加小数了吗?这两个调用之间没有操作,那么为什么会出现这些小数呢?

    1 回复  |  直到 11 年前
        1
  •  1
  •   KristoferA    15 年前

    分类税率是浮动的吗?如果是这样,则将浮点赋值为双精度。额外的小数是由于双精度更高,所以双精度最接近浮点的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());
    

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