Reputation: 691
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}
Upvotes: 44
Views: 41044
Reputation: 3694
Cast the number to a decimal
, then use its ToString
with formatting "#,##0.##"
.
The format means "for values > 3 digits, use thousand separators. Always show a digit before the decimal separator. Optionally show up to 2dp."
decimal a = 5000000;
decimal b = 5000;
decimal c = 5;
decimal d = 2.5m;
decimal e = 0.0005m;
decimal f = 0.45m;
decimal g = 0.499m;
decimal h = 0.51515m;
decimal i = 123456.789m;
decimal j = 10.1m;
// Answers in my English localization
string format = "#,##0.##";
Console.WriteLine("a=" + a.ToString(format)); // 5,000,000
Console.WriteLine("b=" + b.ToString(format)); // 5,000
Console.WriteLine("c=" + c.ToString(format)); // 5
Console.WriteLine("d=" + d.ToString(format)); // 2.5
Console.WriteLine("e=" + e.ToString(format)); // 0
Console.WriteLine("f=" + f.ToString(format)); // 0.45
Console.WriteLine("g=" + g.ToString(format)); // 0.5
Console.WriteLine("h=" + h.ToString(format)); // 0.52
Console.WriteLine("i=" + i.ToString(format)); // 123,456.79
Console.WriteLine("j=" + j.ToString(format)); // 10.1
If you require 2dp, use "#,##0.00"
instead, but this will always show .00 for a whole number.
Upvotes: 0
Reputation: 75
This can be achieved using CultureInfo. Use the below using statement to import the library.
using System.Globalization;
For the decimal conversion, ## can be used for optional decimal places and 00 can be used for mandetory decimal places. Check the below examples
double d1 = 12.12;
Console.WriteLine("Double :" + d1.ToString("#,##0.##", new CultureInfo("en-US")));
String str= "12.09";
Console.WriteLine("String :" + Convert.ToDouble(str).ToString("#,##0.00", new CultureInfo("en-US")));
String str2 = "12.10";
Console.WriteLine("String2 with ## :" + Convert.ToDouble(str2).ToString("#,##0.##", new CultureInfo("en-US")));
Console.WriteLine("String2 with 00 :" + Convert.ToDouble(str2).ToString("#,##0.00", new CultureInfo("en-US")));
int integ = 2;
Console.WriteLine("Integer :" + Convert.ToDouble(integ).ToString("#,##0.00", new CultureInfo("en-US")));
the results are as follows
Double :12.12
String :12.09
String2 with ## :12.1
String2 with 00 :12.10
Integer :2.00
Upvotes: 1
Reputation: 65
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
Upvotes: 4
Reputation: 532435
decimal num = 10.11M;
Console.WriteLine( num.ToString( "0.##" ) );
Upvotes: 48