Custom Numeric Format Negative section bug

Not sure that it is 100% bug but behavior really strange. My task is properly format fraction. For example if :

 int numerator = -7;
 int denominator = 100;

Then if next line of code applied:

string fraction = numerator.ToString("#/"+ denominator +";-#/" + denominator +";0");

which is according to microsofts's section separator logic : https://msdn.microsoft.com/en-us/library/0c899ak8%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396#The

should produce "7/100" if numerator positive (7), "-7/100" if numerator negative (-7) and "0" if numerator 0. Because format string look like this "#/100;-#/100;0"

But for some reason it is not properly working for negative case scenario. If numerator positive all behave as expected, but if it is negative for some reason it will substituted last digit in produced string. So I end up with output like this: "-/107". Any thoughts?

Jon Skeet
people
quotationmark

Your format string is "#/100;-#/100;0". That's a very strange format string. You're saying:

  • If the number is positive, use a format of "#/100".
  • If the number is negative, use a format of "-#/100".
  • If the number is zero, use a format of "0".

For both of the first two cases, you've got 3 digit placeholders, the first of which is optional (so will only appear if there are 3 or more digits to print) and the last two of which are required (so they'll show 0 otherwise). The "/" and "1" characters have no special meaning, so they'll appear as they are.

So we have:

   1 => /101
  12 => /112
 123 => 1/123
  -1 => -/101
 -12 => -/112
-123 => -1/123

All of that is working as documented - just not how you wanted it to work. It sounds like you perhaps wanted to quote the 100 so that the 0s didn't end up as placeholders. A format string of "#/'100';-#/'100';0" produces output of:

   1 => 1/100
  12 => 12/100
 123 => 123/100
  -1 => -1/100
 -12 => -12/100
-123 => -123/100

... but I'd suggest producing that without using a format string at all:

string text = numerator == 0 ? "0" : numerator + "/" + denominator;

people

See more on this question at Stackoverflow