Unexpected Inequality Due to Floating-Point Inaccuracies : float Point Number « Data Type « C# / CSharp Tutorial






class MainClass
{
  static void Main()
  {
    decimal decimalNumber = 4.1231232M;
    double doubleNumber1 = 0.1F * 42F;
    double doubleNumber2 = 0.1D * 42D;
    float floatNumber = 0.1F * 42F;
    
    System.Console.WriteLine("{0} != {1}", decimalNumber, (decimal)doubleNumber1);
    
    System.Console.WriteLine("{0} != {1}", (double)decimalNumber, doubleNumber1);
    
    System.Console.WriteLine("(float){0}M != {1}F",(float)decimalNumber, floatNumber);
    
    System.Console.WriteLine("{0} != {1}", doubleNumber1, (double)floatNumber);
    
    System.Console.WriteLine("{0} != {1}", doubleNumber1, doubleNumber2);
    
    System.Console.WriteLine("{0}F != {1}D", floatNumber, doubleNumber2);
    
    System.Console.WriteLine("{0} != {1}", (double)4.2F, 4.2D);
    
    System.Console.WriteLine("{0}F != {1}D", 4.2F, 4.2D);
  }
}








2.22.float Point Number
2.22.1.Floating-Point Types
2.22.2.The Methods and Fields Supported by Single
2.22.3.The Methods and Fields Supported by Double
2.22.4.float point value literal: 3.281f and 5E-02
2.22.5.Floating point ranges
2.22.6.Unexpected Inequality Due to Floating-Point Inaccuracies