C#中的double类型精度

3
我有这段C#代码。
double result = 480 - 460.8;

为什么结果是19.199999999999989而不是19.2?

1
因为它是双精度数?如果你想要那样的效果,你需要使用Math.Round()函数。 - undefined
public static void Main() { double x = 480 - 460.8; } - undefined
我不想四舍五入。 - undefined
欢迎来到浮点数问题。 - undefined
2
这就是为什么C#有一个decimal类型。 - undefined
1个回答

10

你需要格式化双精度result输出:

double result = 480 - 460.8; 
String.Format("{0:0.##}", result);

测试示例:

https://ideone.com/27OfP4

更新:

还有另一种方法可以不用字符串格式化,您可以使用Math.Round方法保留小数点后两位:

Math.Round(result,2);

example:

https://ideone.com/2Q6RPD


@Elham Azadfar 阅读此关于双精度数的 round 方法的教程:https://www.dotnetperls.com/math-round - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接