use*_*565 4 .net c# format formatting currency
我在C#中遇到货币格式问题.我正在使用框架2.0.
当我使用这段代码时:
CultureInfo culture = new CultureInfo("fr-FR", false);
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "CHF";
Run Code Online (Sandbox Code Playgroud)
price.Value.ToString("C", numberFormatInfo)似乎给了我一个金额与货币之间的空格的字符串.那太糟了!我绝对需要一个不间断的空间!到底是怎么回事?我错过了格式属性还是C#标准?
谢谢你的帮助!
所以基本上你想要price.Value.ToString("C",numberFormatInfo).Replace('','\ u00A0');? 至少应该是非破坏空间的代码. - 科拉克
与上面的评论员完全相同,但使用asci-values代替; > price.Value.ToString("C",numberFormatInfo).Replace((char)32,(char)160); (160是很多>更容易记住,至少对我来说:)) - 弗林德伯格
根据我对问题的解释添加一个答案,@Corak 似乎分享了这个答案。
// Convert "breaking" spaces into "non-breaking" spaces (ie the html )
price.Value.ToString("C", numberFormatInfo).Replace((char) 32, (char) 160);
Run Code Online (Sandbox Code Playgroud)
用 unicode 做同样的事情(由@Corak 的链接提供):
// Convert "breaking" spaces into "non-breaking" spaces without int cast to char
price.Value.ToString("C", numberFormatInfo).Replace(' ', '\u00A0');
Run Code Online (Sandbox Code Playgroud)
顺便说一句(roslyn repl):
> '\u00A0' == (char) 160
true
Run Code Online (Sandbox Code Playgroud)
如果您要大量使用它,还可以使用扩展方法:
public static class StringExtensions
{// CurrencyType is your currency type, guessing double or decimal?
public static string ToCurrencyString(this CurrencyType value, IFormatInfo format)
{
return value.ToString("C", format).Replace((char) 32, (char) 160);
}
}
Run Code Online (Sandbox Code Playgroud)
使用:
numberFormatInfo.CurrencyPositivePattern = 1;
Run Code Online (Sandbox Code Playgroud)
对于值1格式是n$其中$的货币符号,在你的情况下CHF
CurrencyNegativePattern或CurrencyPositivePattern属性,返回一个确定以下内容的整数:
- 货币符号的位置.
- 负值是由前导负号,尾随负号还是括号表示.
- 是否在数值和货币符号之间出现空格.
请尝试以下代码:
CultureInfo culture = new CultureInfo("fr-FR", false);
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "CHF";
numberFormatInfo.CurrencyPositivePattern = 1;
decimal d = 123.23M;
var temp = d.ToString("C", numberFormatInfo);
Run Code Online (Sandbox Code Playgroud)
输出:
123,23CHF
Run Code Online (Sandbox Code Playgroud)
你可以更换它。
price.ToString("C", numberFormatInfo).Replace(" ", "")
Run Code Online (Sandbox Code Playgroud)
或更好地设置NumberFormatInfo.CurrencyPositivePattern为1
numberFormatInfo.CurrencySymbol = "CHF";
numberFormatInfo.CurrencyPositivePattern = 1;
Run Code Online (Sandbox Code Playgroud)
完整示例;
CultureInfo culture = new CultureInfo("fr-FR", false);
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "CHF";
numberFormatInfo.CurrencyPositivePattern = 1;
Console.WriteLine((1.5M).ToString("C", numberFormatInfo));
Run Code Online (Sandbox Code Playgroud)
输出将是;
1,50CHF
Run Code Online (Sandbox Code Playgroud)
这里有一个演示。
CurrencyNegativePattern 或 CurrencyPositivePattern 属性,它返回一个决定以下内容的整数:
货币符号的位置。
负值是否由前导负号、尾随负号或括号表示。
数值和货币符号之间是否出现空格。