简体   繁体   中英

Format a decimal to correct currency using correct number of decimals (C#)

Having a decimal variable 'price' and a RegionInfo variable 'region' like this:

var price = new Decimal(49.9);
var region = new RegionInfo(Thread.CurrentThread.CurrentUICulture.LCID);

I do like this:

string.Format("{0:0,0.##} {1}", price, region.CurrencySymbol);

This will return the desired price string for two of the three cultures I wish to support (Swedish and Norwegian). Although for the third culture (Danish) it will erroneously place the currency symbol after the amount.

This is an alternative approach:

string.Format("{0:c}", price);

This works for all three cultures but now my problem is that I cannot control the number of decimal values.

My question is: How do I simultaneously control the number of decimal values and currency culture?

I am looking for something like this (which of course does not work):

string.Format("{0:c,0.##}", price);

You should use NumberFormat property of a culture, as it already contains information about how many decimals should be included, but you can override it if you set the CurrencyDecimalDigits property of it.

Example from MSDN :

class NumberFormatInfoSample {

  public static void Main() {

  // Gets a NumberFormatInfo associated with the en-US culture.
  NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;

  // Displays a negative value with the default number of decimal digits (2).
  Int64 myInt = -1234;
  Console.WriteLine( myInt.ToString( "C", nfi ) );

  // Displays the same value with four decimal digits.
  nfi.CurrencyDecimalDigits = 4;
  Console.WriteLine( myInt.ToString( "C", nfi ) );

  }
}

/* 
This code produces the following output.

($1,234.00)
($1,234.0000)
*/

If I understood you correctly, isn't this what you want?

var price = new Decimal(49.9);
var cultureInfo = new CultureInfo("da-DK");
//var currentCultureInfo = new CultureInfo(CultureInfo.CurrentCulture.Name);    

var test = string.Format(cultureInfo, "{0:C2}", price);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM