【问题标题】:How to display number to 2 decimal places in mvc3,C#? [duplicate]如何在 mvc3,C# 中将数字显示到小数点后 2 位? [复制]
【发布时间】:2012-10-28 10:12:12
【问题描述】:

可能重复:
Using String Format to show decimal upto 2 places or simple integer
How to set decimal point in 2 decimal places?

我的视图中有价格字段。它具有以下值2.5 and 44. 我想将此值显示给2.50 and 44.00 我使用以下代码

@{decimal prolistprice = decimal.Parse(item.OtherFields["Price"].ToString());}
  $@Math.Round(prolistprice, 2, MidpointRounding.AwayFromZero)

其中item.OtherFields["price"] is a object我将其转换为字符串,然后转换为十进制

但 Math.round 不工作它只显示 2.5 和 44.. 任何人都可以帮助这个

【问题讨论】:

标签: c# asp.net asp.net-mvc-3


【解决方案1】:

Math.Round 就是这样做的 - 循环。

要格式化数字,您可以使用.ToString(formatString),如下所示:

item.OtherFields["price"].ToString("0.00")

【讨论】:

  • ToString 没有重载方法需要 1 个参数
  • @niico 您可能在可空类型上调用ToString。如果是这样,你将不得不做youVariable.Value.ToString("0.00")。不过不要忘记先进行空检查!
【解决方案2】:

使用字符串格式化函数

1. string.Format("{0:n2}", 200000000.8776);
2. string.Format("{0:n3}", 200000000.8776);
3. string.Format("{0:n2}", 0.3);

/* OUTOUT
1. 200,000,000.88
2. 200,000,000.878
3. 0.30
*/

【讨论】:

    【解决方案3】:

    这应该适合你

    yourvalue.ToString ("0.00");
    

    【讨论】:

      【解决方案4】:
      decimal dValue = 2.5;
      string sDisplayValue = dValue.ToString("0.00");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-14
        • 1970-01-01
        • 1970-01-01
        • 2022-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多