关于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

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值