[英]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.