Question

I'm converting an ancient VB6 program to C# and I came across some VB6 code that looked like this . . .

   Format(part(PI).far_xdev, " #0.000;-#0.000")

at first I was confused about the two format fields separated by a semicolon. But it turns out that in VB6 this means that it uses the first one if the value of the number being formatted is 0 or positive, and the second if it's negative. If there were three formatting fields it would be positive, negative, and zero; four would be positive, negative, zero and null.

What's the equivalent of this in C# string formatting? How do I say "use this formating string for a positive number and that one for a negative number"?

(To whoever added the "This question may already have an answer": the problem with that link is that the linked question was asked in reference to some version of BASIC (based on the syntax) and did not explicitly say he was looking for an answer in C#, and neither of the two answers given specifically say they are in C#. We are left to surmise the languages involved based only on the tags. I think this new question and the resulting answers are much more clear, explicit and detailed)

Was it helpful?

Solution

Use the same separation by semi-column. Read more about that separator at msdn (supports up to three sections)

Console.WriteLine("{0:positive;negative;zero}", +1); //prints positive
Console.WriteLine("{0:positive;negative;zero}", -1); //prints negative
Console.WriteLine("{0:positive;negative;zero}", -0); //prints zero

You can use ToString on numeric value and pass format there

string formatted = 1.ToString("positive;negative;zero"); //will return "positive"

or use string.Format as shown in the comment section. But still you need to pass order position {0} to it.

string formatted = string.Format("{0:positive;negative;zero}", 1); 

In order to check for null, you can use null coalescing operator (cast to object is required, since there is no implicit cast from int? to string). It becomes quite messy, so I would recommend to consider simple if statement.

int? v = null;
var formatted = string.Format("{0:positive;negative;zero}", (object) v ?? "null");

OTHER TIPS

C# supports the same custom formatting:

string.Format("{0:#0.000;-#0.000}",part(PI).far_xdev);

Note that the format you use is the same as the standard fixed-point format with 3 significant digits:

string.Format("{0:F3}",part(PI).far_xdev);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top