c# Decimal to string for currency

Tom Gullen picture Tom Gullen · May 3, 2012 · Viewed 63.6k times · Source

To display a currency we do:

ToString("0.##")

For value 5.00 the output is:

5

For value 5.98 the output is:

5.98

For value 5.90 the output is:

5.9

I need the third case to come out with 2 decimal points, eg:

5.90

How can I do this without it affecting the other results?

Answer

Jonathan Wood picture Jonathan Wood · May 3, 2012

Try:

s.ToString("#,##0.00")

Or just:

s.ToString("C")

I know of no built-in way to expand out all two decimal places only when both are not zero. Would probably just use an if statement for that.

int len = s.Length;
if (s[len - 2] == '0' && s[len - 1] == '0')
    s = s.Left(len - 3);