gpt4 book ai didi

c# - 打印 double 值

转载 作者:太空狗 更新时间:2023-10-29 22:06:39 26 4
gpt4 key购买 nike

在我的系统上,以下代码打印“3.6”:

double a = 1.2;
int b = 3;

double c = a * b;

Console.WriteLine(c);

但是在调试器中,我可以看到 c 有一个超过 2 位数的值:

enter image description here

我知道我可以使用 Console.WriteLine("{0:R}", c) 显示完整表示。这是显示 double 实际值的唯一推荐方式吗?


更新

继续上面的例子,我想打印 c 这样如果用户要获取打印的值并使用 == 将其插入回测试代码中,则比较结果为真。在这种情况下,c == 3.5999999999999996 返回 true。

最佳答案

Console.WriteLine 调用使用 "G" format specifierDouble.ToString .这使用当前区域性来确定小数位数(“en-US”为 1)。

如果你想显示 8 位小数,你可以使用 numeric format specifier :

Console.WriteLine(c.ToString("N8"));

Standard Numeric Format Strings

编辑:调试器使用此方法将 double 型转换为字符串:

_ecvt_s

我认为这是最便宜的转换方式。

我在哪里找到它:How does Visual Studio display a System.Double during debugging?

关于c# - 打印 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14077590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com