货币格式 [英] Currency formatting
问题描述
这应该是一个简单的问题,但...
This should be an easy problem but...
我需要的格式在C#显示器(串)的货币
I need to format a currency for display (string) in C#
在考虑中的货币将有自己的规则,如使用的符号,如果该符号应该前值(例如$ 10)或后(如10₫这是越南盾)。
The currency in question will have its own rules such as the symbol to use and if that symbol should come before the value (e.g. $ 10) or after (e.g. 10 ₫ which is Vietnamese Dong).
但如何将数字的格式取决于用户的地方,而不是货币。
But how the numbers are formatted depends upon the users local, not the currency.
例如。
1.234,56 ₫ should be displayed to a user in Vietnam but
1,234.56 ₫ should be displayed to a user in the US
(格式为code所以很容易看到的差异,和。)的
所以,code像
Double vietnamTotal = 1234.56;
return vietnamTotal.ToString("c");
不会工作,因为它会使用用户(或更为准确CultureInfo.CurrentCulture)区域的格式和货币,所以你会得到像$ 1,123.56 - 正确使用和。但错误的符号。
Won't work as it will use the users (or more accuratly CultureInfo.CurrentCulture) locale for format and currency so you would get things like $1,123.56 - right use of , and . but wrong symbol.
Double vietnamTotal = 1234.56;
CultureInfo ci = new CultureInfo(1066); // Vietnam
return vietnameTotal.ToString("c",ci));
请问给1.234,56₫ - 右符号,错误的使用,和。对于当前用户。
Would give 1.234,56 ₫ - Right symbol, wrong use of , and . for current user.
这篇文章<一个href="http://stackoverflow.com/questions/850673/proper-currency-format-when-not-displaying-the-native-currency-of-a-culture">gives在正确的事更详细的事,但不知道如何做到这一点。
This post gives more detail on the right thing to do, but not how to do it.
我缺少什么明显的方法隐藏在框架是什么?
What obvious method hidden in the framework am I missing?
推荐答案
- 取
的NumberFormatInfo
从用户的货币,它克隆 - 将
CurrencySymbol
在有关克隆格式的CurrencySymbol
货币 - 如果要使用的货币位置(和格式的一些其他方面)复制,
设置
CurrencyPositivePattern
和CurrencyNegativePattern
以相同的方式。 - 使用结果的格式。
- Take the
NumberFormatInfo
from the user's currency, and clone it - Set the
CurrencySymbol
in the cloned format to theCurrencySymbol
of the currency in question - If you want the currency position (and some other aspects of the format) to be copied,
set
CurrencyPositivePattern
andCurrencyNegativePattern
in the same way. - Use the result to format.
例如:
using System;
using System.Globalization;
class Test
{
static void Main()
{
decimal total = 1234.56m;
CultureInfo vietnam = new CultureInfo(1066);
CultureInfo usa = new CultureInfo("en-US");
NumberFormatInfo nfi = usa.NumberFormat;
nfi = (NumberFormatInfo) nfi.Clone();
NumberFormatInfo vnfi = vietnam.NumberFormat;
nfi.CurrencySymbol = vnfi.CurrencySymbol;
nfi.CurrencyNegativePattern = vnfi.CurrencyNegativePattern;
nfi.CurrencyPositivePattern = vnfi.CurrencyPositivePattern;
Console.WriteLine(total.ToString("c", nfi));
}
}
诚然我的控制台不管理,以显示正确的符号,但我敢肯定,这只是由于字体问题:)
Admittedly my console doesn't manage to display the right symbol, but I'm sure that's just due to font issues :)
这篇关于货币格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!