这种方法将在应用指定的文化时达到预期的结果:
decimal a = 100.05m;
decimal b = 100.50m;
decimal c = 100.00m;
CultureInfo ci = CultureInfo.GetCultureInfo("de-DE");
string sa = String.Format(new CustomFormatter(ci), "{0}", a); // Will output 100,05
string sb = String.Format(new CustomFormatter(ci), "{0}", b); // Will output 100,50
string sc = String.Format(new CustomFormatter(ci), "{0}", c); // Will output 100
您可以将文化替换为 CultureInfo.CurrentCulture 或任何其他文化以满足您的需求。
CustomFormatter 类是:
public class CustomFormatter : IFormatProvider, ICustomFormatter
{
public CultureInfo Culture { get; private set; }
public CustomFormatter()
: this(CultureInfo.CurrentCulture)
{ }
public CustomFormatter(CultureInfo culture)
{
this.Culture = culture;
}
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (formatProvider.GetType() == this.GetType())
{
return string.Format(this.Culture, "{0:0.00}", arg).Replace(this.Culture.NumberFormat.NumberDecimalSeparator + "00", "");
}
else
{
if (arg is IFormattable)
return ((IFormattable)arg).ToString(format, this.Culture);
else if (arg != null)
return arg.ToString();
else
return String.Empty;
}
}
}