kazinix
kazinix

Reputation: 30103

Format function to display custom character(s) if number is zero

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

Upvotes: 2

Views: 407

Answers (1)

Pranay Rana
Pranay Rana

Reputation: 176896

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.

Upvotes: 7

Related Questions