如果要将 42.0000001 格式化为 42
可以修改下面的解决方案来做到这一点。
但基本上,您只想从字符串中删除 .00..。
您可以使用 RegEx 来做到这一点:
public string Format(string format, double value)
{
var regex = new Regex(@"^(?<IntPart>.*)([.,]0*)$");
var s = String.Format("{0:F4}", value);
var match = regex.Match(s);
if (match.Success)
{
return match.Groups["IntPart"].Value;
}
return s;
}
Console.WriteLine(Format("{0:F4}", 1.35687)); // 1.3569
Console.WriteLine(Format("{0:F4}", 1.35)); // 1.3500
Console.WriteLine(Format("{0:F4}", 1)); // 1
Console.WriteLine(Format("{0:F4}", 42.000001)); // 42
如果要将 42.0000001 格式化为 42.0000。
您需要测试该值的小数部分(准确为 0)。
我认为很好地执行它的唯一方法是使用ICustomFormatter。
我将创建 F_XX 格式,根据变量是否为 F0 或 FXX整数与否。 (在您的情况下,F_4 将是 F0 或 F4)。
这里是第一次尝试,:
public class MyCustomFormatter : IFormatProvider, ICustomFormatter
{
// Match "F_XX" where XX are digits.
private readonly Regex _regex = new Regex("F_(?<DigitCount>\\d+)");
// IFormatProvider.GetFormat implementation.
public object GetFormat(Type formatType)
{
// Determine whether custom formatting object is requested.
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
var shouldUseF0 = false;
var match = _regex.Match(format);
// Detect F_XX format.
if (match.Success)
{
// Manage float.
if (arg is float)
{
if (((float) arg)%1 == 0)
{
shouldUseF0 = true;
}
}
// Manage double.
if (arg is double)
{
if (((double) arg)%1 == 0)
{
shouldUseF0 = true;
}
}
// TODO: Manage int, long...
if (shouldUseF0)
{
format = "F0";
}
else
{
// Build the FXX format.
format = "F" + match.Groups["DigitCount"].Value;
}
}
if (arg is IFormattable) return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
if (arg != null) return arg.ToString();
return String.Empty;
}
}
结果如下:
Console.WriteLine(String.Format(cf, "{0:F_4}", 1.35678)); // 1.3568
Console.WriteLine(String.Format(cf, "{0:F_4}", 1.35)); // 1.3500
Console.WriteLine(String.Format(cf, "{0:F_4}", 1.00)); // 1