關於C#的decimal、float、double的精度問題(坑)

float類型,沒問題:

float x = 0.7f;
Console.WriteLine("x=" + x.ToString());//x = 0.7
int a = (int)x;
Console.WriteLine("a=" + a.ToString());//a = 0

float x10 = x * 10;
Console.WriteLine("x10=" + x10.ToString());//x10 = 7.0
int a10 = (int)x10;
Console.WriteLine("a10=" + a10.ToString());//a10 = 7

 

double類型,沒問題:

double x = 0.7;
Console.WriteLine("x=" + x.ToString());//x = 0.7
int a = (int)x;
Console.WriteLine("a=" + a.ToString());//a = 0

double x10 = x * 10;
Console.WriteLine("x10=" + x10.ToString());//x10 = 7.0
int a10 = (int)x10;
Console.WriteLine("a10=" + a10.ToString());//a10 = 7

 

float轉double類型,精度不對:

double x = 0.7f;//float轉double
Console.WriteLine("x=" + x.ToString());//x = 0.699999988079071
int a = (int)x;
Console.WriteLine("a=" + a.ToString());//a = 0

double x10 = x * 10;
Console.WriteLine("x10=" + x10.ToString());//x10 = 6.99999988079071
int a10 = (int)x10;
Console.WriteLine("a10=" + a10.ToString());//a10 = 6

 

double和decimal:

bool b1 = (0.1 + 0.2 == 0.3);
Console.WriteLine(b1 ? "true" : "false");//false
bool b2 = (0.1m + 0.2m == 0.3m);
Console.WriteLine(b2 ? "true" : "false");//true

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章