In C#, the comparison of floating point numbers and decimal

floating point number

The floating-point number type of C#, float, double, when we define a floating-point number: we
can use the var keyword, and we can do type inference to
define the float type, and we need to add F or f at the end of the number

//定义一个double类型
double a1=1.1;
var a2 = 1.1;
Console.WriteLine(a2.GetType());
//定义一个float类型,数字末尾需要加上 F或者是f 
float b1=1.1f;
var b2 =1.1f; 
Console.WriteLine(b1.GetType());

The calculation of floating point numbers will have errors:

 //浮点数的比较,出现了差错:
 double a = 1.3;
 double b = 1.1;
 double c = 0.2;

 if (a - b == c)
 {
    
    
     Console.WriteLine("ok");
 }
 else
 {
    
    
     Console.WriteLine(a - b);
     Console.WriteLine("no");
 }

The result is as follows:
insert image description here

decimal

Use decimal to define, you need to add M or m at the end of the number

var c1 = 1.1m;
decimal c2 = 1.1M;
Console.WriteLine(c1.GetType());

Calculate using decimal:

 //使用decimal类型
 decimal d = 1.3m;
 decimal e = 1.1m;
 decimal f = 0.2m;
 if (d - e == f)
 {
    
    
     Console.WriteLine(d - e);
     Console.WriteLine("ok");
 }
 else
 {
    
    
     Console.WriteLine("no");
 }

The results are as follows:
insert image description here
Therefore, please use the decimal type for operations and comparisons involving floating-point numbers.

Guess you like

Origin blog.csdn.net/mrtwenty/article/details/126449939