C# 双精度数除法时的精度损失
下面的函数传递一个字符串“1004233”并打印以下输出:
D1 = 1.004233
D2 = 0.00423299999999993
D3 = 4232.99999999993
D4 = 4232
我需要 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;
}
The function bellow is passed a string "1004233" and prints the following output:
D1 = 1.004233
D2 = 0.00423299999999993
D3 = 4232.99999999993
D4 = 4232
I need D4 to print 4233 and not 4232. How do i stop this precision loss from happening?
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是标准浮点问题。
请改用
十进制
。尽管十进制也没有无限精度,但它们是以 10 为基数实现的,因此它们会给您期望的结果。
This is the standard floating-point question.
Use a
decimal
instead.Although
decimal
s also don't have infinite precision, they are implemented in base 10, so they will give you the results you expect.使用十进制算术而不是浮点(双精度)。更多信息请参见:
Use decimal arithmetic instead of floating-point (double). More information to be found: