Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Decimal places using c#

Tags:

c#

formatting

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.

like image 916
Kiran Reddy Avatar asked May 25 '12 06:05

Kiran Reddy


People also ask

What is 2f in C?

2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.

How do I get 2 decimal places in C++?

We use the %. 2f format specifier to display values rounded to 2 decimal places.

How do you write decimal numbers in C?

Rounding is not required. For example, 5.48958123 should be printed as 5.4895 if given precision is 4. In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf().


2 Answers

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 up to two decimal places(e.g. 2.10 would be shown as 2.1 ).

Use "{0:.00}", if you want always show two decimal places(e.g. 2.10 would be shown as 2.10 )

Or if you want the currency symbol displayed use the following:

String.Format("{0:C}", Debitvalue) 
like image 189
WoofWoof88 Avatar answered Sep 29 '22 02:09

WoofWoof88


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

decimal DEBITAMT = Math.Round(1156.547m, 2); 
like image 32
Nikhil Agrawal Avatar answered Sep 29 '22 02:09

Nikhil Agrawal