Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format decimal to two places or a whole number

For 10 I want 10 and not 10.00 For 10.11 I want 10.11

Is this possible without code? i.e. by specifying a format string alone simlar to {0:N2}

like image 729
Neil Avatar asked Jan 27 '10 15:01

Neil


People also ask

How do you format two decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do I format to 2 decimal places in Word?

Click the Table Tools' Layout tab, select Data and then click Formula. Click the Number Format menu and select 0.00 for two decimals.


2 Answers

decimal num = 10.11M;  Console.WriteLine( num.ToString( "0.##" ) ); 
like image 198
tvanfosson Avatar answered Sep 24 '22 02:09

tvanfosson


It seems to me that the decimal precision is intrinsic to the decimal type, which defaults to 4 decimal places. If I use the following code:

decimal value = 8.3475M; Console.WriteLine(value); decimal newValue = decimal.Round(value, 2); Console.WriteLine(newValue); 

The output is:

8.3475 8.35 
like image 44
GeoffDev Avatar answered Sep 25 '22 02:09

GeoffDev