使用c#的两个小数位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10749506/
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
Two Decimal places using c#
提问by Kiran Reddy
decimal Debitvalue = 1156.547m;
decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:0.00}", Debitvalue));
I have to get only two decimal places but by using this code I am getting 1156.547. Let me know which format I have to use to display two decimal places.
我只需要得到两位小数,但通过使用此代码,我得到了 1156.547。让我知道我必须使用哪种格式来显示两位小数。
采纳答案by cjk
If you want to round the decimal, look at Math.Round()
如果你想四舍五入小数,看看 Math.Round()
回答by Nikhil Agrawal
Use Math.Round()for rounding to two decimal places
使用Math.Round()四舍五入至小数点后两位
decimal DEBITAMT = Math.Round(1156.547m, 2);
回答by COLD TOLD
here is another approach
这是另一种方法
decimal decimalRounded = Decimal.Parse(Debitvalue.ToString("0.00"));
回答by WoofWoof88
Your question is asking to display two decimal places. Using the following String.format will help:
您的问题是要求显示两位小数。使用以下 String.format 会有所帮助:
String.Format("{0:.##}", Debitvalue)
this will display then number with only two decimal places.
这将显示只有两位小数的数字。
Or if you want the currency symbol displayed use the following:
或者,如果您希望显示货币符号,请使用以下内容:
String.Format("{0:C}", Debitvalue)
回答by Dimitar Tsonev
Another option is to use the Decimal.Round Method
另一种选择是使用Decimal.Round 方法
回答by Esteban Perez
I use
我用
decimal Debitvalue = 1156.547m;
decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:F2}", Debitvalue));
回答by Kabilan Smart
Another way :
其它的办法 :
decimal.Round(decimalvalue, 2, MidpointRounding.AwayFromZero);
decimal.Round(decimalvalue, 2, MidpointRounding.AwayFromZero);
回答by AH.
Probably a variant of the other examples, but I use this method to also make sure a dot is shown before the decimal places and not a comma:
可能是其他示例的变体,但我使用此方法还确保在小数位之前显示一个点而不是逗号:
someValue.ToString("0.00", CultureInfo.InvariantCulture)
回答by Kevin Infante
The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use
如果您想始终显示两位小数(即使您的数字只有一位小数),最好的方法是使用
yournumber.ToString("0.00");
回答by Md. Shafiqur Rahman
For only to display, property of Stringcan be used as following..
仅用于显示,String可以使用的属性如下..
double value = 123.456789;
String.Format("{0:0.00}", value);
Using System.Math.Round. This value can be assigned to others or manipulated as required..
使用System.Math.Round. 该值可以分配给其他人或根据需要进行操作。
double value = 123.456789;
System.Math.Round(value, 2);

