ToString(字符串)不格式化浮点数?正如我所料

Jak*_*ith 2 c# number-formatting

我正在使用WinForms应用程序,格式化后在视图中显示一个字符串.

以下是我尝试格式化数字的方法:

reportData.VelocityRangeStart.ToString(reportData.Velocity.FormatString)
Run Code Online (Sandbox Code Playgroud)

下面是在Visual Studio中使用立即窗口的结果:

reportData.VelocityRangeStart
12.5996475    // output
reportData.Velocity.FormatString
"#,##0.000"    // output
reportData.VelocityRangeStart.ToString(reportData.Velocity.FormatString)
"12.59965"    // output
12.5996475f.ToString("#,##0.000")
"12.600"    // output
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下我缺少的东西吗?我希望"12.600"在那种情况下.仅供参考:reportData.VelocityRangeStart属于float?类型.

Sam*_*nen 6

Nullable类型甚至不应该ToString()使用格式字符串重载.您需要使用它reportData.VelocityRangeStart.Value.ToString(reportData.Velocity.FormatString)来进行格式化工作.

并且不要忘记先在值中检查null!所以

reportData.VelocityRangeStart.HasValue ? reportData.VelocityRangeStart.Value.ToString(reportData.Velocity.FormatString) : "is null"
Run Code Online (Sandbox Code Playgroud)