Nick Rolando
Nick Rolando

Reputation: 26177

Formatting string - money value

I'm trying to format my double to be in US dollar currency format, but I do not want trailing 00's if the value comes out to be a whole number.

I have tried

String.Format("{0:#,0.#0}", cost);

and

String.Format("{0:#,0.##}", cost);

The former is leaving me trailing 00 on whole number, and the latter is will give me 55.6 where I want 55.60. How can I format my value to meet both of these needs?

Upvotes: 2

Views: 8034

Answers (4)

David Anderson
David Anderson

Reputation: 13680

You can use the Currency ("C") Format Specifier by calling ToString. No actual work required.

Example

string s = cost.ToString("C0"); // Where 0 is the precision

You can't do anything conditional in a single call like omit precision display, but you could do it through some extension methods.

static class CurrencyExtensions
{
    public static String ToCurrency(this decimal d) { // Extend Decimal
        if (d % 1 != 0) return d.ToString("C2");
        return d.ToString("C0");
    }

    public static String ToCurrency(this double d) { // Extend Double
        if (d % 1 != 0) return d.ToString("C2");
        return d.ToString("C0");
    }
}

Example Usage

decimal amount1 = 4m;
decimal amount2 = 4.25m;

string s1 = amount1.ToCurrency(); // $4
string s2 = amount2.ToCurrency(); // $4.25

The advantage of doing it this way over others is that it handles culture information for you, and is a much more elegant solution.

Upvotes: 1

Firoz Ansari
Firoz Ansari

Reputation: 2515

Try

string val = decimal.Parse("2.00").ToString("G29")


?decimal.Parse("2.00").ToString("G29")
"2"
?decimal.Parse("2.02").ToString("G29")
"2.02"
?decimal.Parse("12.0045").ToString("G29")
"12.0045"
?decimal.Parse("0.0045").ToString("G29")
"0.0045"
?decimal.Parse("0.00").ToString("G29")
"0"
?decimal.Parse("0.05").ToString("G29")
"0.05"

Upvotes: 2

James Johnson
James Johnson

Reputation: 46067

Try something like this:

var output = string.Format(((Math.Round(num) == num) ? "{0:0}" : "{0:0.00}"), num);

Upvotes: 4

Philippe Leybaert
Philippe Leybaert

Reputation: 171864

I don't think that's possible with a standard format string, but a trick would be:

Regex.Replace(String.Format("{0:#,##0.00}", cost),"\\.00$","");

or:

string s = String.Format("{0:#,##0.00}", cost);

if (s.EndsWith(".00"))
   s = s.Substring(0,s.Length-3);

I know, it's ugly...

Upvotes: 2

Related Questions