Addition of Double values inconsistent

后端 未结 7 2003
渐次进展
渐次进展 2021-01-20 01:13

I came across following issue while developing some engineering rule value engine using eval(...) implementation.

    Dim first As Double = 1.1
    Dim secon         


        
7条回答
  •  无人共我
    2021-01-20 01:39

    You are not adding decimals - you are adding up doubles.

    Not all doubles can be represented accurately in a computer, hence the error. I suggest reading this article for background (What Every Computer Scientist Should Know About Floating-Point Arithmetic).

    Use the Decimal type instead, it doesn't suffer from these issues.

    Dim first As Decimal = 1.1
    Dim second As Decimal = 2.2
    Dim sum As Decimal= first + second
     If (sum = 3.3) Then
        Console.WriteLine("Matched")
    Else
        Console.WriteLine("Not Matched")
    End If
    

提交回复
热议问题