[英]Format decimal c# - Keep last zero
我一直在寻找这个,但似乎无法找到答案。 我有以下小数与我想要的String.Format相应的输出
100.00 - > 100
100.50 - > 100.50
100.51 - > 100.51
我的问题是我似乎无法找到一种格式,它将0保持在100.50的末尾,并从100中删除2个零。
任何帮助深表感谢。
编辑更清晰。 我有十进制类型的变量,它们只会是2位小数。 基本上我想显示2个小数位,如果它们存在或没有,我不想在100.50变为100.5的情况下显示一个小数位
据我所知,没有这样的格式。 您必须手动实现此功能,例如:
String formatString = Math.Round(myNumber) == myNumber ?
"0" : // no decimal places
"0.00"; // two decimal places
你可以用这个:
string s = number.ToString("0.00");
if (s.EndsWith("00"))
{
s = number.ToString("0");
}
测试您的号码是否为整数,并使用以下格式:
string.Format((number % 1) == 0 ? "{0}": "{0:0.00}", number)
好吧,这会伤害我的眼睛,但应该给你你想要的东西:
string output = string.Format("{0:N2}", amount).Replace(".00", "");
更新:我更喜欢海因兹的回答。
应用指定的文化时,此方法将实现所需的结果:
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.