Format decimal to two places or a whole number
38,742
Solution 1
decimal num = 10.11M;
Console.WriteLine( num.ToString( "0.##" ) );
Solution 2
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
Comments
-
Neil almost 2 years
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}
-
Dave Bish almost 13 yearsThis doesn't work - decimal num = 10.1; The best I can come up with is: num .ToString("C").Replace(".00", ""); Anyone who has the answer for this case would be helping me!
-
tvanfosson almost 13 years@Dave - what doesn't work? Is it that you want exactly 2 decimals unless they are zero?
-
tvanfosson almost 13 years@Dave - How about
num % 1 == 0 ? num.ToString("0") : num.ToString("0.00");
You could implement it as an extension method on decimal. -
Microsoft Developer about 10 yearsConsole.WriteLine( num.ToString( "0.00" ) ); forces 2 DP even if the value is zero. i..e "0.00" or "0.10" etc. Don't forget default behavior is to round up from .005 not down.
-
tvanfosson about 10 years@dotNETNinja that's what Dave was asking for. In retrospect I might do
decimal.Truncate(num) == num
instead of mod by 1, though. -
Radu Simionescu about 9 yearsthis worked for me under mono... if you really have to use string operations to get this right, don't forget string.trimRight(new char[]{'0'}) to trim any trailing zeros - but do check that there is a decimal separator first
-
Andrew over 8 yearsI think this doesn't answer what Neil asked.