【问题标题】:casting number to IFormattable not working as expected将数字转换为 IFormattable 未按预期工作
【发布时间】: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


    【解决方案1】:

    问题是使用“-”会导致它被视为具有零精度,它会四舍五入到 -0,实际上是 0。这会导致它根据零大小写进行格式化。 From the docs for custom formatting:

    如果要格式化的数字非零,但根据第一节或第二节的格式四舍五入后变成零,则根据第三节的格式对生成的零进行格式化。

    【讨论】:

    • 这是否意味着可以更改 FormatCode 以提供我想要的?像这样:“0.000;-.000;0”?
    • @JakeSmith 如果你使用它,你会得到-0.49 - 如果这是你想要的,那么是的;)
    • 哈哈不,我想要“-”,如果它在任何数量级都是负数。我会继续谷歌搜索,但如果你认为你可能有办法做到这一点,我很乐意讨论它:)
    • @JakeSmith 如果不通过格式之外的其他逻辑运行它,您可以将任何以“-”开头的字符串转换为“-”,例如..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多