c# - 为什么 C# 中的数字格式字符串在不使用小数 (F0) 时将数字四舍五入?

标签 c# .net

当涉及到 C# 中的标准数字格式字符串时,我遇到了一些非常奇怪的事情。这可能是一个已知的怪癖,但我找不到任何记录它的东西,我也想不出一种方法来实际得到我想要的东西。

我想取一个像 17.929333333333489 这样的数字并将其格式化为不带小数位。所以我只想要“17”。但是当运行这段代码时。

decimal what = 17.929333333333489m;
Console.WriteLine(what.ToString("F0"));

我得到了这个输出

18

查看 Microsoft 关于它的文档,他们的示例显示了相同的输出。

https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx

//          F:                     -195489100.84
//          F0:                    -195489101
//          F1:                    -195489100.8
//          F2:                    -195489100.84
//          F3:                    -195489100.838

这是一个显示奇怪问题的代码示例。

http://csharppad.com/gist/d67ddf5d0535c4fe8e39

此问题不仅限于“F”和“N”等标准项,还包括“#”等自定义项。

我怎样才能使用标准的“F0”格式化程序而不用它四舍五入我的号码?

最佳答案

来自 Standard Numeric Format Strings 上的文档:

xx is an optional integer called the precision specifier. The precision specifier ranges from 0 to 99 and affects the number of digits in the result. Note that the precision specifier controls the number of digits in the string representation of a number. It does not round the number itself. To perform a rounding operation, use the Math.Ceiling, Math.Floor, or Math.Round method.

When precision specifier controls the number of fractional digits in the result string, the result strings reflect numbers that are rounded away from zero (that is, using MidpointRounding.AwayFromZero).

因此文档确实讨论了这一点,并且没有明显的方法来防止纯粹通过格式字符串对输出进行舍入。

我能提供的最好方法是使用 Math.Truncate() 自行截断数字:

decimal what = 17.929333333333489m;
decimal truncatedWhat = Math.Truncate(what);
Console.WriteLine(truncatedWhat.ToString("F0"));

关于c# - 为什么 C# 中的数字格式字符串在不使用小数 (F0) 时将数字四舍五入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35808409/

相关文章:

c# - 为什么这段代码不能证明读/写的非原子性?

c# - 使用 IdentityServer 向特定客户端验证特定用户

css - 部署更改 CSS 字体值

javascript - 使用身份服务器 4 匿名访问 SignalR hub

c# - 使用 JSON 序列化/反序列化 TimeSpan

c# - 如何*轻松*公开底层对象的方法?

c# - 为什么 linq 扩展方法返回具体类型

c# - 嵌套在动态创建的 CheckBoxList 中的 foreach

c# - 如何在C#中修复这些错误?

c# - 为什么 EventInfo.RemoveEventHandler 抛出 NullReferenceException?