문제

I'm having trouble with casting a number to IFormattable, calling ToString(...) on it, and passing a FormatCode of the from 0.000;-;0 meaning that I want to display three decimal places of precision if the number is positive, display a "-" if negative, and show zero if it is zero (without the three decimal places of precision). The negativity of the number is not picked up if the magnitude of the number does not exceed 0.5.

Here is my public accessor for my FormattedValue:

public string FormattedValue
{
    get
    {
        if (Value is IFormattable)
        {
            return (Value as IFormattable)
                       .ToString(FormatCode,
                                 System.Threading.Thread.CurrentThread.CurrentUICulture);
        }
        else
        {
            return Value.ToString();
        }
    }
}

For example, if I execute the line

(-0.5 as IFormattable)
    .ToString("0.000;-;0", 
              System.Threading.Thread.CurrentThread.CurrentUICulture)

I get what I expect: "-". However when I pass in something just slightly lower, say,

(-0.499 as IFormattable)
    .ToString("0.000;-;0", 
              System.Threadings.Thread.CurrentThread.CurrentUICulture)

I get "0" returned.

Does anyone know why this is not working? This is really important because a lot of the values I'm trying to format in this way are going to be of smaller magnitude than what seems to work with this approach. Any way I can get this to work the way I want? Thanks!

Update

This is what ended up working for me:

Math.Abs(value) < 0.0005
    ? value.ToString("0.000")
    : value.ToString("0.000;-;-");
도움이 되었습니까?

해결책

The problem is that using "-" causes it to be treated as having zero precision, which rounds to -0, which is effectively 0. This causes it to be formatted according to the zero case. 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top