【问题标题】:ToString(string) not formatting a float? as I would expect it toToString(string) 没有格式化浮点数?正如我所期望的那样
【发布时间】:2016-02-01 04:54:42
【问题描述】:

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

这是我尝试格式化数字的方式:

reportData.VelocityRangeStart.ToString(reportData.Velocity.FormatString)

以下是在 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

有人可以解释我缺少什么吗?在这种情况下,我希望"12.600"。仅供参考:reportData.VelocityRangeStart 属于 float? 类型。

【问题讨论】:

  • 请查看minimal reproducible example 指导 - 您发布的任何代码都非常混乱。
  • reportData.VelocityRangeStart的类型是什么?将其转换为浮点数会首先改变结果吗?
  • 如果你这样做reportData.VelocityRangeStart.Value.ToString(reportData.Velocity.FormatString),它还会这样做吗?
  • @AlexeiLevenkov,删除了这些笑话。如果您一次粘贴整个内容,代码仍然无法编译。但是,如果您复制并粘贴每个输入行,您的指尖就很方便了。

标签: c# number-formatting


【解决方案1】:

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

并且不要忘记首先检查值中的空值!所以

reportData.VelocityRangeStart.HasValue ? reportData.VelocityRangeStart.Value.ToString(reportData.Velocity.FormatString) : "is null"

【讨论】:

  • 非常感谢。这种行为是否表明存在错误?
  • 而他确实提到的地方是使用可空类型。 @Sami 或者它只是黑暗中的一个箭头
  • @Dot_NETPro 也许就在最后说的类型?
  • @JakeSmith 这就是 Nullable 类型的工作方式。由于并非所有类型都具有带有格式字符串的 ToString(),因此我假设他们没有将其添加到 Nullable 本身,并且必须手动处理。
  • 我删除了最后一段中不必要的措辞,以更加强调我提到的类型以供将来参考。
【解决方案2】:

我想你想用这个:

float VelocityRangeStart=12.5996475F;
string strVelocityRangeStart=VelocityRangeStart.ToString();
Console.WriteLine((Math.Ceiling(Double.Parse(strVelocityRangeStart)).ToString()));

【讨论】:

  • 我很确定他们不希望这样。试试看它输出了什么。
  • Math.Ceiling(reportData.VelocityRangeStart).ToString() error CS1503: Argument 1: cannot convert from 'float?' to 'decimal'
猜你喜欢
  • 2016-08-16
  • 1970-01-01
  • 2016-12-03
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 2013-09-26
相关资源
最近更新 更多