Using String Format to show decimal up to 2 places or simple integer
This is a common formatting floating number use case.
Unfortunately, all of the built-in one-letter format strings (eg. F, G, N) won't achieve this directly.
For example, num.ToString("F2")
will always show 2 decimal places like 123.40
.
You'll have to use 0.##
pattern even it looks a little verbose.
A complete code example:
double a = 123.4567;
double b = 123.40;
double c = 123.00;
string sa = a.ToString("0.##"); // 123.46
string sb = b.ToString("0.##"); // 123.4
string sc = c.ToString("0.##"); // 123
An inelegant way would be:
var my = DoFormat(123.0);
With DoFormat
being something like:
public static string DoFormat( double myNumber )
{
var s = string.Format("{0:0.00}", myNumber);
if ( s.EndsWith("00") )
{
return ((int)myNumber).ToString();
}
else
{
return s;
}
}
Not elegant but working for me in similar situations in some projects.
Sorry for reactivating this question, but I didn't find the right answer here.
In formatting numbers you can use 0
as a mandatory place and #
as an optional place.
So:
// just two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"
You can also combine 0
with #
.
String.Format("{0:0.0#}", 123.4567) // "123.46"
String.Format("{0:0.0#}", 123.4) // "123.4"
String.Format("{0:0.0#}", 123.0) // "123.0"
For this formating method is always used CurrentCulture
. For some Cultures .
will be changed to ,
.
Answer to original question:
The simpliest solution comes from @Andrew (here). So I personally would use something like this:
var number = 123.46;
String.Format(number % 1 == 0 ? "{0:0}" : "{0:0.00}", number)