lko
lko

Reputation: 8289

Can C#'s string currency format optionally up to 6 decimal numbers?

With a quick test C#'s currency format doesn't appear to support optional decimal places.

CultureInfo ci = new CultureInfo("en-US");
String.Format(ci, "{0:C2}", number); // Always 2 decimals
String.Format(ci, "{0:C6}", number); // Always 6 decimals

Trying to customize it doesn't work.

String.Format(ci, "{0:C0.00####}", number); // two decimals always, 4 optional

Is it possible to use the currency format with an optional number of decimals?

e.g. $199.99 or $0.009999 or $5.00 are shown like this.

Upvotes: 3

Views: 2092

Answers (2)

Steven Liekens
Steven Liekens

Reputation: 14088

It's a bit long-winded, but you could first calculate the number of decimal places. Then, you can use that number to form your format string.

You'll need this utility function (credits go to a guy by the name of Joe):

private int CountDecimalPlaces(decimal value)
{
    value = decimal.Parse(value.ToString().TrimEnd('0'));
    return BitConverter.GetBytes(decimal.GetBits(value)[3])[2];
}

Then you can do something along these lines:

decimal number = 5.0M;

CultureInfo ci = CultureInfo.CurrentCulture;

NumberFormatInfo nfi = ci.NumberFormat.Clone() as NumberFormatInfo;

// Count the decimal places, but default to at least 2 decimals
nfi.CurrencyDecimalDigits = Math.Max(2 , CountDecimalPlaces(number));

// Apply the format string with the specified number format info
string displayString = string.Format(nfi, "{0:c}", number);

// Ta-da
Console.WriteLine(displayString);

Upvotes: 2

Habib
Habib

Reputation: 223277

I am not sure if there is a direct way for doing that with using C but you can do:

decimal number = 1M;
CultureInfo ci = new CultureInfo("en-US");
string formattedValue = string.Format("{0}{1}", 
                                    ci.NumberFormat.CurrencySymbol, 
                                    number.ToString("0.00####")); 

Upvotes: 1

Related Questions