Two Decimal places using c#

2019-01-11 21:43发布

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.

标签: c# formatting
10条回答
干净又极端
2楼-- · 2019-01-11 21:52

Another option is to use the Decimal.Round Method

查看更多
等我变得足够好
3楼-- · 2019-01-11 21:53

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");
查看更多
叼着烟拽天下
4楼-- · 2019-01-11 21:54

Your question is asking to display two decimal places. Using the following String.format will help:

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)
查看更多
Luminary・发光体
5楼-- · 2019-01-11 21:54

Use Math.Round() for rounding to two decimal places

decimal DEBITAMT = Math.Round(1156.547m, 2);
查看更多
ゆ 、 Hurt°
6楼-- · 2019-01-11 21:55

here is another approach

decimal decimalRounded = Decimal.Parse(Debitvalue.ToString("0.00"));
查看更多
家丑人穷心不美
7楼-- · 2019-01-11 22:01

I use

decimal Debitvalue = 1156.547m;
decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:F2}", Debitvalue));
查看更多
登录 后发表回答