gpt4 book ai didi

c# - 将数字转换到 IFormattable 无法按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:54 25 4
gpt4 key购买 nike

我在将数字转换为 IFormattable、在其上调用 ToString(...) 并传递 from 0.000;-;0 的 FormatCode 时遇到问题,这意味着我想显示正数精确到小数点后三位,负数显示“-”,为零显示零(不带小数点后三位)。如果数字的大小不超过 0.5,则不会提取数字的负数。

这是我的 FormattedValue 的公共(public)访问器:

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;-;-");

最佳答案

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

If the number to be formatted is nonzero, but becomes zero after rounding according to the format in the first or second section, the resulting zero is formatted according to the third section.

关于c# - 将数字转换到 IFormattable 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23417854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com