【发布时间】:2014-05-01 22:37:39
【问题描述】:
我在将数字转换为 IFormattable、对其调用 ToString(...) 并传递来自 0.000;-;0 的 FormatCode 时遇到问题,这意味着如果数字是,我想显示三位小数的精度正,负则显示“-”,为零则显示零(不包括小数点后三位)。如果数的大小不超过0.5,则数的负数不被拾取。
这是我的 FormattedValue 的公共访问器:
public string FormattedValue
{
get
{
if (Value is IFormattable)
{
return (Value as IFormattable)
.ToString(FormatCode,
System.Threading.Thread.CurrentThread.CurrentUICulture);
}
else
{
return Value.ToString();
}
}
}
例如,如果我执行该行
(-0.5 as IFormattable)
.ToString("0.000;-;0",
System.Threading.Thread.CurrentThread.CurrentUICulture)
我得到了我的期望:“-”。但是,当我传入稍微低一点的东西时,比如说,
(-0.499 as IFormattable)
.ToString("0.000;-;0",
System.Threadings.Thread.CurrentThread.CurrentUICulture)
我得到“0”返回。
有谁知道为什么这不起作用?这真的很重要,因为我试图以这种方式格式化的许多值将比这种方法似乎工作的值要小。有什么办法能让我按照我想要的方式工作吗?谢谢!
更新
这就是最终对我有用的东西:
Math.Abs(value) < 0.0005
? value.ToString("0.000")
: value.ToString("0.000;-;-");
【问题讨论】:
标签: c# formatting object-to-string