如何在 mvc3,C# 中将数字显示为 2 个小数位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13285240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:04:20  来源:igfitidea点击:

How to display number to 2 decimal places in mvc3,C#?

c#asp.netasp.net-mvc-3

提问by Prakash

Possible Duplicate:
Using String Format to show decimal upto 2 places or simple integer
How to set decimal point in 2 decimal places?

可能的重复:
使用字符串格式显示最多 2 位小数或简单整数
如何在小数点后 2 位设置小数点?

I have Price field in my view. it have the following values 2.5 and 44.I want to display this value to 2.50 and 44.00i use the following code

我有价格字段在我看来。它有以下值2.5 and 44.我想显示这个值2.50 and 44.00我使用下面的代码

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

in which item.OtherFields["price"] is a objecti convert it to string and then decimal

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

but Math.round is not working it shows 2.5 and 44 only.. Can anyone help this

但 Math.round 不起作用,它只显示 2.5 和 44 .. 谁能帮忙

采纳答案by PeteGO

Math.Rounddoes just that - round.

Math.Round就是这样 - 圆。

To format the number you may use .ToString(formatString)like so:

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

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

回答by KroaX

This should work for you

这应该适合你

yourvalue.ToString ("0.00");

回答by Lawrence Johnson

decimal dValue = 2.5;
string sDisplayValue = dValue.ToString("0.00");

回答by Naresh Pansuriya

Use string format function

使用字符串格式函数

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
*/