- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在将数字转换为 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/
IFormattable有没有好的引用实现?我打算至少定制一个 IFormatProvider对于我的对象,我想确保传递给 IFormattable.ToString(string, IFormatP
string listOfItemPrices = items.ToSemiColonList(item => string.Format("{0:C}", item.Price.ToString()
String.Format 和 IFormattable.ToString(format, value) 在尝试格式化为十六进制时提供不同的结果。使用 IFormattable.ToString(fo
我有一个处理字符串输入的函数。 public string Foo(string text) { // do stuff with text and /
我在将数字转换为 IFormattable、在其上调用 ToString(...) 并传递 from 0.000;-;0 的 FormatCode 时遇到问题,这意味着我想显示正数精确到小数点后三位,
我对 .NET 中不同形式的序列化缺乏一致性感到有点沮丧: DataContractSerializer - 使用新属性或旧的 [Serializable] 属性,但序列化程序本身并不像其他一些 WC
FormattableString 已在 C# 6.0 中引入。因为我们可以使用 string 对象使用相同的字符串格式,所以为什么需要使用 FormattableString 或 IFormatta
ReSharpers StringFormatMethodAttribute 是跟踪执行字符串格式化的方法的参数的好方法。 所以我以这种方式实现了一个方法: [StringFormatMethod("
IFormattable、IFormatProvider和ICustomFormatter有什么区别和联系,什么时候用?一个简单的实现示例也会非常好。 我并不是说什么时候在 .net 框架中使用它,而
第一次在 .net C# 中使用二进制格式 来自MSDN的代码是这样的: IFormatter formatter = new BinaryFormatter(); Stream stream =
我是一名优秀的程序员,十分优秀!