【问题标题】:How can I use string.Format() to truncate instead of round?如何使用 string.Format() 截断而不是舍入?
【发布时间】:2023-12-20 14:04:01
【问题描述】:

我想以这样一种方式应用string.Format(),使其执行截断而不是舍入。例如

string.Format("##", 46.5); // output is 47, but I want 46
string.Format("##.#", 46.55); // output is 46.6, but I want 46.5

【问题讨论】:

标签: c# rounding string.format


【解决方案1】:

在格式化输出之前使用Math.Truncate截断

【讨论】:

  • 这是“截断”(带 n),顺便说一句
  • 我认为这不是他想要的 46.55 为 46.5。 Math.Truncate 将返回 46。
  • var v = Math.Truncate(46.5); v.ToString("##.#") // 给出 46
  • 此答案不使用格式字符串来获得所需的结果。