字符串格式化为货币C#

时间:2014-04-03 11:55:19

标签: c# asp.net

我是在ASP.NET中构建Web应用程序的新手,我正试图在肯尼亚先令中显示货币。先令的符号是KES。

我有这个:

<span>
    <b>Price: </b><%#:String.Format(new System.Globalization.CultureInfo("sw-KE"), "{0:c}", Item.BeatPrice)%> 
</span>

文化名称来自http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.80%29.aspx

但是,价格显示为S3,000而不是KES 3,000

我需要做什么才能正确格式化价格?

6 个答案:

答案 0 :(得分:3)

如果格式不符合您的预期,您可以添加自定义字符串格式:

String.Format("KES {0:N3}", Item.BeatPrice)

希望这有效。

答案 1 :(得分:3)

最好不要对CurrencySymbol进行硬编码,因此您应该使用

var regionInfo = new RegionInfo("sw-KE");
var currencySymbol = regionInfo.ISOCurrencySymbol;

为您的文化获取正确的CurrencySymbol。

<强> //编辑: 或者您可以尝试此功能:

public static string FormatCurrency(decimal value)
{
    CultureInfo cultureInfo = Thread.CurrentThread.CurrentUICulture;
    RegionInfo regionInfo = new RegionInfo(cultureInfo.LCID);
    string formattedCurrency = String.Format("{0} {1:C}", regionInfo.ISOCurrencySymbol, value);
    return formattedCurrency.Replace(cultureInfo.NumberFormat.CurrencySymbol, String.Empty).Trim();

}

它为您提供基于当前UICulture的格式化货币字符串。

答案 2 :(得分:1)

如果您的机器的区域设置已正确设置,则可以使用:

Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0:c}", Item.BeatPrice));

它会根据您机器的区域设置自动获取文化。

答案 3 :(得分:1)

Ondrej Svejdar 所说,有两个符号,如$ vs. USD:

var region = new System.Globalization.RegionInfo("sw-KE");

Console.WriteLine(region.CurrencySymbol);  // "S"
Console.WriteLine(region.ISOCurrencySymbol);  // "KES"

注意:当我ran this on IDEone(使用Mono编译)时,结果出乎意料(&#34; KES&#34;&#34; Kenyan Shilling&#34;)。

答案 4 :(得分:1)

使用String.Format“c”或“C”时,为您提供指定文化的货币符号。您正在尝试显示肯尼亚先令的货币ISO代码。下面的代码将准确显示您想要的内容。

String.Format("{0} {1}", (new RegionInfo("sw-KE")).ISOCurrencySymbol, Item.BeatPrice)

如果您没有简单地在应用程序上更改文化,请执行此操作。

String.Format("{0} {1}", "KES", Item.BeatPrice)

答案 5 :(得分:0)

最佳做法是将字符串格式化为货币格式{0:C}并将当前线程UICulture或Culture更改为KES,并且ASP.NET足够智能以显示符合您的currunt文档的页面。

注意: 您可以通过改变浏览器的文化来改变文化(您可以为了开发目的而这样做)但是最佳实践以编程方式改变文化,例如在这里我改变了用户Cookie的文化基础和mu默认文化是en-us像这样。

protected override void InitializeCulture()
{
    HttpCookie cultureCookie = Request.Cookies["culture"];

    if (cultureCookie == null)
    {
        cultureCookie = new HttpCookie("culture", "en-US");
        Response.Cookies.Add(cultureCookie);
    }

    Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureCookie.Value);
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureCookie.Value);

    base.InitializeCulture();
}
相关问题