Reputation: 9009
Is there a string format that can be used on a decimal so that the following results are obtained?
123 => "123"
123.4 => "123.40"
123.45 => "123.45"
123.456 => "123.46"
In English, the number should always be displayed with exactly two decimals, except when it holds an integer value, when it should have no decimals (so no "123.00" displays are allowed).
Upvotes: 4
Views: 1332
Reputation: 11607
You should use Math.Round method first and then use a toString() Conversion
//123.456 => "123.46"
myDecimal = Math.Round(myDecimal, 2);
The second parameter being the number of decimal places to round to and then you do the following :
myDecimal.ToString();
No real need for the N2 actually, this way you display numbers "as is" after rounding, ie, 124 if there is no decimals after point, or 123.46 after rounding 123.456
Upvotes: 0
Reputation: 8145
Something like this?
public static string ToSpecialFormatString(this decimal val)
if (val == Math.Floor(val))
{
return val.ToString("N0");
}
return val.ToString("N2");
}
Upvotes: 0
Reputation: 1503829
I don't know of any such format, I'm afraid. You might need to use:
string text = (d == (int) d) ? ((int) d).ToString() : d.ToString("N2");
EDIT: The code above will only work when d
is in the range between int.MinValue
and int.MaxValue
. Obviously you can do better than that using long
, but if you want to cover the full range of decimal
you'll need something a little more powerful.
Upvotes: 1
Reputation: 5813
You can use "#.##" as your format string. So:
123.23.ToString("#.##") => 123.23
123.00.ToString("#.##") => 123
One caveat is that:
123.001.ToString("#.##") => 123
But whether or not that's acceptable is up to you.
Upvotes: 0
Reputation: 126982
Perhaps not ideal, but a starting point. Simply format to 2 decimal places and replace any .00 with an empty string.
decimal a = 123;
decimal b = 123.4M;
decimal c = 123.456M;
Debug.Assert(a.ToString("0.00").Replace(".00", "") == "123");
Debug.Assert(b.ToString("0.00").Replace(".00", "") == "123.40");
Debug.Assert(c.ToString("0.00").Replace(".00", "") == "123.46");
Upvotes: 0