【问题标题】:How do I round the number in a textbox to 2 decimals in C#?如何在 C# 中将文本框中的数字四舍五入为 2 位小数?
【发布时间】:2012-08-13 10:56:45
【问题描述】:

我有一个价格文本框,我想得到一个带有 2 个小数的十进制值,无论原始字符串是已经是小数还是整数。例如:

input = 12 --> output = 12.00
input = 12.1 --> output = 12.10
input = 12.123 --> output = 12.12

【问题讨论】:

  • 请注意,接受的答案为您提供的字符串可能并不总是您想要的。例如,(12.125m).ToString("N")"12.13"(12.135m).ToString("N")"12.14"AwayFromZero 舍入)。但是Math.Round(12.125m, 2);12.12Math.Round(12.135m, 2);12.14。小心!

标签: c# parsing integer decimal


【解决方案1】:

您可以使用将字符串作为格式的.ToString() 重载:

var roundedInput = input.ToString("0.00");

当然,这会产生一个字符串类型。

简单的取整,可以使用Math.Round:

var roundedInput = Math.Round(input, 2);

您应该知道,默认情况下,Math.Round 使用您可能不想要的“银行家四舍五入”方法。在这种情况下,您可能需要使用采用舍入类型枚举的重载:

var roundedInput = Math.Round(input, 2, MidpointRounding.AwayFromZero);

在此处查看使用MidpointRounding 的方法重载文档:http://msdn.microsoft.com/en-us/library/ms131275.aspx

还要注意Math.Round 的默认舍入方法与decimal.ToString() 中使用的默认舍入方法不同。例如:

(12.125m).ToString("N");  // "12.13"
(12.135m).ToString("N");  // "12.14"
Math.Round(12.125m, 2);   // 12.12
Math.Round(12.135m, 2);   // 12.14

根据您的情况,使用错误的技术可能会非常糟糕!

【讨论】:

    【解决方案2】:

    使用这个方法decimal.ToString("N");

    【讨论】:

      【解决方案3】:
      // just two decimal places
      String.Format("{0:0.00}", 123.4567);      // "123.46"
      String.Format("{0:0.00}", 123.4);         // "123.40"
      String.Format("{0:0.00}", 123.0);         // "123.00"
      

      【讨论】:

        【解决方案4】:

        试试

        Input.Text = Math.Round(z, # Places).ToString();
        

        【讨论】:

        • 这会返回四舍五入的答案,但不会按要求完成格式化
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-05
        • 1970-01-01
        • 2016-03-10
        • 2010-09-20
        • 1970-01-01
        • 2014-09-26
        相关资源
        最近更新 更多