2

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;-;-");
Jake Smith
  • 2,332
  • 1
  • 30
  • 68

1 Answers1

2

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Does this mean the FormatCode can be altered to give me what I want? Like this: "0.000;-.000;0"? – Jake Smith May 01 '14 at 22:52
  • @JakeSmith If you use that, you'll get `-0.49` - if that's what you want, then yes ;) – Reed Copsey May 01 '14 at 23:04
  • haha nope, I want "-" if it is negative at any magnitude. I'll keep Googling around, but if you think you might have a way to do this, I would love to discuss it :) – Jake Smith May 02 '14 at 15:55
  • @JakeSmith Not without running it through some other logic outside of the format - you could convert any string beginning with "-" into "-", for example.. – Reed Copsey May 02 '14 at 16:55