Home > Net >  Is there a int to string format that turns zero into a blank?
Is there a int to string format that turns zero into a blank?

Time:02-20

I'm displaying int values to the screen as strings, but if the value is zero (or less, I suppose) I want the string to be blank. To check that I'd need a set of if statements and to store the int value temporarily just to check it (or else retrieve it twice.) I'm wondering if there is a ToString format that will automatically do that, like how I can use ToString("N0") to add commas. That way I can just directly set the string value in a single line.

CodePudding user response:

Here is an example of that functionality:

int x = 0;
int y = 5;
Console.WriteLine(string.Format("test 1: {0}", x <= 0 ? "" : x));
Console.WriteLine(string.Format("test 2: {0}", y <= 0 ? "" : y));

Output:

test 1: 
test 2: 5

CodePudding user response:

You can make use of an extension method as shown below:

namespace System { public static class StringExtensions { public static string FormartIntZeroORLessToEmpty(this int value) { if(value <= 0) { return string.Empty; } return value.ToString(); } } }

  • Related