我使用{0:C5}
显示最多5个小数位的货币值,但如果有无效的零,则不会显示它们。
使用简单的小数点我只需使用{0:0.#####}
但我需要使用货币格式化程序,因为它是一个多语言系统。
编辑:忘记提及我正在使用复合格式https://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx
答案 0 :(得分:1)
您可以在正常格式化后使用.TrimEnd(new Char[] { '0' } )
来摆脱前导零。
var number = (0.476434323).ToString("C5").TrimEnd(new Char[] { '0' } );
答案 1 :(得分:1)
也许明确地放置货币符号? e.g:
String.Format(cultureInfo, "{0}{1:0.#####}", cultureInfo.NumberFormat.CurrencySymbol, 1.00005M))
另见How to Remove the Trailing Zeros of Precision From a C# Decimal
答案 2 :(得分:1)
您可以从十进制值中检索有效位数,然后使用您获得的数字生成货币格式
private string GenerateCurrencyFormatFor(decimal value)
{
const decimal NORMALIZE_COEFFICENT = 1.000000000000000000000000000000000m;
const int MAX_DIGITS = 5;
decimal normalizeValue = value/ NORMALIZE_COEFFICENT;
var decimalBits = decimal.GetBits(normalizeValue);
var decimalScaleInfo = decimalBits[3];
var scaleInfoBytes = BitConverter.GetBytes(decimalScaleInfo);
var significantDigitsCount = (int)scaleInfoBytes[2];
var actualDigitsCount = Math.Min(significantDigitsCount, MAX_DIGITS);
return $"C{actualDigitsCount}";
}
当然,你甚至可以在一个班轮中“重构”这个功能,但我希望它能够表明这个想法。
然后使用它
var value = 123.4500m;
var currencyFormat = GenerateCurrencyFormatFor(value);
var printValue = value.ToString(currencyFormat);
// will print £123.45
var value = 123.1234567m; // will print £123,12346
答案 3 :(得分:0)
解决方案是使用IFormatProvider
和ICustomFormatter
public class NumberFormatter : IFormatProvider, ICustomFormatter
{
//TODO: Get your own NumberFormatInfo from CurrentCulture instead of this.
private static readonly NumberFormatInfo NumberFormatInfo = CultureInfo.CreateSpecificCulture("en-US").NumberFormat;
public object GetFormat(Type formatType)
{
if (formatType != typeof(ICustomFormatter))
{
throw new InvalidOperationException("Invalid Format");
}
return this;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
var supportedTypes = new Type[] { typeof(decimal), typeof(double), typeof(int), typeof(float) };
if (!supportedTypes.Contains(arg.GetType()))
{
return null;
}
if (format.ToUpper() != "C")
{
return null;
}
var result = arg.ToString();
var isFraction = result.IndexOf(".", System.StringComparison.Ordinal) > 0;
if (isFraction)
{
result = RemoveTrailingZero(result);
var numberOfDigits = result.Substring(result.IndexOf(".", System.StringComparison.Ordinal) + 1).Length;
if (numberOfDigits < 5)
{
NumberFormatInfo.CurrencyDecimalDigits = numberOfDigits;
NumberFormatInfo.NumberDecimalDigits = numberOfDigits;
}
else
{
NumberFormatInfo.CurrencyDecimalDigits = 5;
NumberFormatInfo.NumberDecimalDigits = 5;
}
}
return Convert.ToDecimal(result).ToString("C", NumberFormatInfo);
}
private string RemoveTrailingZero(string number)
{
var lastIndexOfZero = number.LastIndexOf("0", System.StringComparison.Ordinal);
if (lastIndexOfZero == number.Length - 1)
{
number = number.Remove(lastIndexOfZero);
return RemoveTrailingZero(number);
}
else
{
return number;
}
}
}
以下是用法和输出
var numberFormatter = new NumberFormatter();
var amount = 10000.1230M;
Console.WriteLine(string.Format(numberFormatter, "Amount is {0:C}", amount));
amount = 10000.12305M;
Console.WriteLine(string.Format(numberFormatter, "Amount is {0:C}", amount));
amount = 10000.00M;
Console.WriteLine(string.Format(numberFormatter, "Amount is {0:C}", amount));
amount = 10000.1010M;
Console.WriteLine(string.Format(numberFormatter, "Amount is {0:C}", amount));
Amount is $10,000.123
Amount is $10,000.12305
Amount is $10,000
Amount is $10,000.101