shenku
shenku

Reputation: 12420

How can I format currency with no decimals but only when the decimal is zero?

I am currently using the following to format a decimal as a currency.

double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));

// Result: $12,345.68

Which is the behaviour I want, except when the decimals are 0, as in double value = 12345.00;

Then the result should be $12,345

I've tried variations using # like .ToString("C.##" etc. but I can't get it to work as I'd like.

Upvotes: 1

Views: 1987

Answers (2)

Jeff Ogata
Jeff Ogata

Reputation: 57783

Using decimal, you could determine which format string to use:

//decimal value = 12345.6789m;
decimal value = 12345.0000m;

var formatString = Decimal.Truncate(value) == value ? "C0" : "C";

Console.WriteLine(value.ToString(formatString, CultureInfo.CurrentCulture));

Upvotes: 4

tofu
tofu

Reputation: 197

how about something like this .ToString("0.##")

Upvotes: 1

Related Questions