2

I'm using the Format function ( http://msdn.microsoft.com/en-us/library/59bz1f0h%28v=vs.90%29.aspx ) to format my output. Currently I use this format string:

 TestStr1 = Format(5459.4, "##,##0.00")
 TestStr2 = Format(0.4, "##,##0.00")
 TestStr3 = Format(0.0, "##,##0.00")

The above code will return "5,459.40", "0.4" and "0.00" respectively. Now, if the value is equal to zero, I want to display "-" instead. How can I achieve that output without using if-else statement, just Format function?

Edit:

Aside from Pranay's article here I found an article from Microsoft, it's on the bottom part. http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

kazinix
  • 28,987
  • 33
  • 107
  • 157

1 Answers1

7

Full Article : Format Number To Display

use

";" Section Separator

This allow to display number according to number sign. As you can see in below code the fmt variable which is format I am going to apply on my number here first format before ; is for positive number , second format is for negative number and last format is for the zero value. Basically its "Positive;negative;zero" format. You can see the what it does in output of this code.

Example :

double posValue = 1234;
double negValue = -1234; 
double zeroValue = 0;

string fmt = "+##;-##;**Zero**";

Console.WriteLine("value is positive : " + posValue.ToString(fmt));    
Console.WriteLine();

Console.WriteLine("value is negative : " +negValue.ToString(fmt));    
Console.WriteLine();

Console.WriteLine("value is Zero : " + zeroValue.ToString(fmt));
Console.WriteLine();

Note:

in above example you just repalce Zero with "-" or char you want.

Although code is in c#.net but same you can achieve it in vb.net after all its ToString function formate change.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • Ha ha! Never thought it would be that easy. In my case, there 'll be no negative values so "##,##0.00;;-" is enough. Thanks! – kazinix Jul 03 '12 at 06:28
  • @dpp - yes its quite easy but most of dev dont know about this kind of thing thats y i wrote aticle on this... – Pranay Rana Jul 03 '12 at 06:30
  • I opened another question, I can't find the solution in your article and MSDN. http://stackoverflow.com/questions/11305822/format-numbers-to-roman-numerals Thanks! – kazinix Jul 03 '12 at 06:50