簡體   English   中英

格式化小數點以使用正確的小數位數(C#)糾正貨幣

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

具有一個十進制變量“ price”和一個RegionInfo變量“ region”,如下所示:

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

我喜歡這樣:

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

這將返回我希望支持的三種文化中的兩種(瑞典和挪威)的理想價格。 盡管對於第三種文化(丹麥語),它將錯誤地將貨幣符號放在金額之后。

這是另一種方法:

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

這適用於所有三種文化,但是現在我的問題是我無法控制十進制值的數量。

我的問題是:如何同時控制小數位數和貨幣區域性?

我正在尋找這樣的東西(這當然不起作用):

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

您應該使用區域性的NumberFormat屬性,因為它已經包含有關應包含多少個小數的信息,但是如果設置了它的CurrencyDecimalDigits屬性,則可以覆蓋它。

來自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)
*/

如果我正確理解了您,這不是您想要的嗎?

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM