In my application, there are possibilities to format a string using the string.Format() function. I want to add the possibility to return blank when the result is zero.
As far as I can see, it is possible to do this using the code: 0.toString("0;; ");, but as i already mentioned, I need to use the string.Format() function (since it must be able to use for example the {0:P} format for percentage.
Does anyone knows how to blank a zero value using the string.Format() function?
String.Format() supports the ; section separator.
Try e.g. String.Format("{0:#%;;' '}", 0);.
My answer is a bit late, but you may want to try the following:
{0:#.##%;-#.##%;''}
why don't you do it with if else statement?
string result = String.Format(the value);
if(result=="0")
{
result=" ";
}
Or, perhaps more elegantly as an extension method on int:
public static class StringFormatters
{
public static string ToNonZeroString(this int i) => i == 0 ? "" : i.ToString();
}
and then
(1+1-2).ToNonZeroString()
Related
In Windows forms C#, I want to check if a textbox I made starts with a numeric value, then if it does I want to insert the minus (-) sign at the beginning to change the number to negative, I found a way but it's too time wasting, here's my code:
if (richTextBox1.Text.StartsWith("1") || richTextBox1.Text.StartsWith("2") #until richTextBox1.Text.StartsWith("9"))
{
richTextBox1.Text.Insert(0, "-");
}
So I was asking, if there's a shorter way to replace that code?
if (Char.IsNumber(richTextBox1.Text[0]))...
You should also add some checks around it to make sure there's text.
Using regex:
if (Regex.IsMatch(richTextBox1.Text, #"^\d"))
Matches a digit (0-9) at the start of the string.
Or a direct replace:
richTextBox1.Text = Regex.Replace(richTextBox1.Text, #"^\d", "-$&");
Checking if the first character of a text is a number can be done in single line, using Char.IsNumber() function as follows:
if ( Char.IsNumber( stringInput, 0) ) {
// String input begins with a number
}
More information:
https://learn.microsoft.com/en-us/dotnet/api/system.char.isnumber
Many good answer's already here, another alternative is if you want culture support give this a try...
public static bool IsNumber(char character)
{
try
{
int.Parse(character.ToString(), CultureInfo.CurrentCulture);
return true;
}
catch (FormatException) { return false; }
}
You can call it like:
if ( IsNumber(richTextBox1.Text[0]))
I have looked around for this, but I'm not sure it's possible with string interpolation (I'm using VS2015).
string sequenceNumber = $"{fieldValuePrefix.ToUpper()}{separator}{similarPrefixes + 1:D4}";
Is there any way to make D4 a variable ? Some say yes, some no. Apparently, VS2015 C#6.0 is able to do it.
This works, it will return a string like WMT-0021, depending on fieldValuePrefix (WMT), separator (-) and the value of similarPrefixes (20). But I'd like the "D4" part to be a method argument instead of hardcoded in there.
Any ideas ?
You can, but you have to use explicit ToString call like this:
string format = "D4";
string sequenceNumber =
$"{fieldValuePrefix.ToUpper()}{separator}{(similarPrefixes + 1).ToString(format)}";
I currently output a currency value left-aligned, using the following:
String.Format(CultureInfo.CurrentCulture, "{0:#,##0}", value);
I wish to modify the string formatter so that I can right align this. Im not sure how to do it without affecting my existing formatter.
Could someone please advise?
EDIT: I Know it involves something similar to:
http://www.csharp-examples.net/align-string-with-spaces/
String.Format("{0,20:#,##0}", value); will do it.
Example.
not very clear what you actually mean, but I suppose, you are talking about
String.PadLeft method.
Example: to "align" right, you can:
string hello ="hello";
int supportedSymbCount = 10;
int padcount = supportedSymbCount - hello.Length;
if(padCount>0)
hello = hello.PadLeft(padCount);
This will add "pads" in front of the string as much as need to compose a string as long as 10 characters. Choose parameters more sutable to you, and it should work in your case.
For console output use the tab character as a separator,
Console.WriteLine( "\t{0:#,##0}", value )
For web use div class="numeric" with text-align="right".
For other outputs there are no generic solutions.
Use PadLeft or PadRight
int iTotalLength = 20; // Total length of string
char cPadChar = '0'; // Padding character
String.Format(CultureInfo.CurrentCulture, "{0:#,##0}", value).PadLeft(iTotalLength,
cPadChar);
public string Format { get { return string.Format("{0}{1}v{1}", LastManStanding ? "FFA " : string.Empty, m_Teams.PlayersPerTeam); } }
should I rather use a StringBuilder?
I'm not really sure how wrong it's to conditionally format strings like that, rather than doing
public string Format
{
get
{
StringBuilder sb = new StringBuilder();
if(LastManStanding)
sb.Append("FFA ");
sb.Append(string.Format("{0}v{0}", m_Teams.PlayersPerTeam);
return sb.ToString();
}
}
For such small strings, what you are doing is fine.
Use StringBuilder when you are dealing with thousands of concatenations and/or string formatting.
Side note:
Instead of:
sb.Append(string.Format("{0}v{0}", m_Teams.PlayersPerTeam));
You can do:
sb.AppendFormat("{0}v{0}", m_Teams.PlayersPerTeam);
Wrong, no. Readable? Meh
A little formatting can go a long way
public string Format
{
get
{
return string.Format("{0}{1}v{1}",
LastManStanding ? "FFA " : string.Empty,
m_Teams.PlayersPerTeam);
}
}
The first version is preferred in my opinion, it clearly expresses your intention and its much more concise and easy to read then the second, lengthy one. I would format it like this though:
public string Format
{
get
{
return string.Format("{0}{1}v{1}", LastManStanding ? "FFA " : string.Empty,
m_Teams.PlayersPerTeam);
}
}
StringBuilder is preferred if you're doing edits on long string, in this case you don't need it.
Agree with everyone - for such small string it is ok. Note that your rewrite with StringBuilder is worse since you use String.Format instead of StringBuilder.AppendFormat.
In your case using single format string to create resulting string is benificial if you ever decide to start localizing your program in other laguages - it is possible to pull formatting tring from resources, but it is very hard to make code with StringBuilder to respect all possible languages.
Actually there could be another side of the story not realted to using StringBuilder or String.Format. Some people/teams prefer not to use ? : operator. Knowing why you were recommended to rewrite piece of code would help to target rewrite.
I'd separate the formatting logic for FFA and normal games:
public string Format
{
get
{
if(LastManStanding)
return string.Format("FFA {0}v{0}", m_Teams.PlayersPerTeam);
else
return string.Format("{0}v{0}", m_Teams.PlayersPerTeam);
}
}
It's much easier to read. And logically the format strings are separate too. It's quite likely that you'll change them separately, and I'm surprised you didn't. "FFA 2v2" doesn't make much sense to me.
I tried writing an extension method to take in a ulong and return a string that represents the provided value in hexadecimal format with no leading zeros. I wasn't really happy with what I came up with... is there not a better way to do this using standard .NET libraries?
public static string ToHexString(this ulong ouid)
{
string temp = BitConverter.ToString(BitConverter.GetBytes(ouid).Reverse().ToArray()).Replace("-", "");
while (temp.Substring(0, 1) == "0")
{
temp = temp.Substring(1);
}
return "0x" + temp;
}
The solution is actually really simple, instead of using all kinds of quirks to format a number into hex you can dig down into the NumberFormatInfo class.
The solution to your problem is as follows...
return string.Format("0x{0:X}", temp);
Though I wouldn't make an extension method for this use.
You can use string.format:
string.Format("0x{0:X4}",200);
Check String Formatting in C# for a more comprehensive "how-to" on formatting output.
In C# 6 you can use string interpolation:
$"0x{variable:X}"
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated