我有一个问题。如果小于1,则找不到将十进制转换为货币字符串而不带前导零的格式。
e.g。
decimal d = 0.14M;
d.ToString("C"); // Translates to $0.14 But I need to get $ .14
是否有一些特殊的精度说明符来丰富这样的效果,只需调用ToString?
答案 0 :(得分:1)
试试这个:
string result = String.Format("{0:#.0}", d);
答案 1 :(得分:0)
decimal d = 0.14M;
var cs = CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol;
string result = String.Format(String.Concat("{0:", cs, " #.00}"), d);
// result == "$ .14" if CurrentCulture is "en-US"
答案 2 :(得分:-1)
如果您想考虑文化,您需要使用NumberFormatInfo
提供的信息。下面是将十进制格式化为货币但没有前导零的扩展方法。如果您不想使用扩展方法,可以轻松地将扩展方法更改为普通方法。
代码中有一个“快捷方式”。它无法处理多个组大小。我不认为可以使用自定义数字格式完成,然后唯一可行的解决方案是使用N
格式化并删除任何前导0
。
static class DecimalExtensions {
public static String ToCurrencyFormat(this Decimal value) {
return ToCurrencyFormat(value, CultureInfo.CurrentCulture);
}
public static String ToCurrencyFormat(this Decimal value, CultureInfo cultureInfo) {
return ToCurrencyFormat(value, cultureInfo.NumberFormat);
}
public static String ToCurrencyFormat(this Decimal value,
NumberFormatInfo numberFormat) {
// Assume the CurrencyGroupSizes contains a single element.
var format =
"#,"
+ new String('#', numberFormat.CurrencyGroupSizes[0])
+ "."
+ new String('0', numberFormat.CurrencyDecimalDigits);
var formattedValue = Math.Abs(value).ToString(format, numberFormat);
if (value >= Decimal.Zero)
return FormatPositiveCurrency(
numberFormat.CurrencyPositivePattern,
numberFormat.CurrencySymbol,
formattedValue
);
else
return FormatNegativeCurrency(
numberFormat.CurrencyNegativePattern,
numberFormat.CurrencySymbol,
formattedValue
);
}
static String FormatPositiveCurrency(Int32 pattern, String symbol, String value) {
switch (pattern) {
case 0:
return symbol + value;
case 1:
return value + symbol;
case 2:
return symbol + " " + value;
case 3:
return value + " " + symbol;
default:
throw new ArgumentException();
}
}
static String FormatNegativeCurrency(Int32 pattern, String symbol, String value) {
switch (pattern) {
case 0:
return "(" + symbol + value + ")";
case 1:
return "-" + symbol + value;
case 2:
return symbol + "-" + value;
case 3:
return symbol + value + "-";
case 4:
return "(" + value + symbol + ")";
case 5:
return "-" + value + symbol;
case 6:
return value + "-" + symbol;
case 7:
return value + symbol + "-";
case 8:
return "-" + value + " " + symbol;
case 9:
return "-" + symbol + " " + value;
case 10:
return value + " " + symbol + "-";
case 11:
return symbol + " " + value + "-";
case 12:
return symbol + " -" + value;
case 13:
return value + "- " + symbol;
case 14:
return "(" + symbol + " " + value + ")";
case 15:
return "(" + value + " " + symbol + ")";
default:
throw new ArgumentException();
}
}
}