[英]C# precision loss when dividing a double
The function bellow is passed a string "1004233" and prints the following output: 函数bellow传递一个字符串“1004233”并打印以下输出:
D1 = 1.004233 D1 = 1.004233
D2 = 0.00423299999999993 D2 = 0.00423299999999993
D3 = 4232.99999999993 D3 = 4232.99999999993
D4 = 4232 D4 = 4232
I need D4 to print 4233 and not 4232. How do i stop this precision loss from happening? 我需要D4打印4233而不是4232.如何阻止这种精确损失的发生?
public string someFunc(String s){
string retval = "0";
try{
int id = int.Parse(s);
double d = (double)id / (double)1000000;
Console.WriteLine("D1 = " + d);
d = d - Math.Truncate(d);
Console.WriteLine("D2 = " + d);
d = d * (double)1000000;
Console.WriteLine("D3 = " + d);
retval = "" + Math.Truncate(d);
Console.WriteLine("D4 = " + retval);
}catch(Exception ex){}
return retval;
}
This is the standard floating-point question . 这是标准的浮点问题 。
Use a decimal
instead. 请改用
decimal
。
Although decimal
s also don't have infinite precision, they are implemented in base 10, so they will give you the results you expect. 虽然
decimal
也没有无限精度,但它们在基数10中实现,因此它们将为您提供预期的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.