-
Check for characters
This causes a fatal error if the input is not a number.
if ((float.Parse(x.Text) >- 1)||(float.Parse(x.Text) < 9999999))
How do I stop the the conversion if the user enters in a character?
How do I check to see if what was entered was a character or number?
-
Throw a textBox on a form called textBox1 and give this a try.
PHP Code:
string outputStr = "";
foreach(char myChar in textBox1.Text)
{
if(Char.IsNumber(myChar))
{
outputStr += myChar.ToString();
}
}
textBox1.Text = outputStr;
textBox1.Select(textBox1.Text.Length, textBox1.Text.Length +1);
Jeremy
-
Put the above in a try catch block.
-
Just off the top of my head, wouldn't that cause a problem if the user entered a decimal number?
-
I'll have to give that a try and experimentation to see how it works.
-
I Like that!!! It is something I was looking for anyways.
-
I figured out a way around the . bug:
if(!Char.IsSymbol(myChar)&&(!Char.IsLetter(myChar)))
-
But I can't get rid of the spaces. Any ideas?
-
PHP Code:
string outputStr = "";
bool bFoundDecimal = false;
foreach(char myChar in textBox1.Text)
{
if(Char.IsNumber(myChar))
{
outputStr += myChar.ToString();
}
else if ((!bFoundDecimal) && (myChar == '.'))
{
// there can only be one decimal!
outputStr += myChar.ToString();
bFoundDecimal = true;
}
}
textBox1.Text = outputStr;
textBox1.Select(textBox1.Text.Length, textBox1.Text.Length +1);
-
So I can substitute this
(myChar == '.')
with this
(myChar == ' ')
to get rid of the spaces and I won't forget to omit the bool for that.
Right?
-
-
Good! Will that work even if the user uses tabs instead of spaces. Or are tabs==spaces.
-
i do not think that tabs are spaces think that tabs are '\t' characters.
Jeremy
-
You may be right. But I hope that tabs are evaluated as one space at a time.
-
In C#, how to determine if the string is a number or not?
-
-
any.
i'm writting a program which highlight source code. because i want to check if the string is a number to mark it.
some examples:
3
3.12
-
What about hexadecimal?
Code:
bool isNumber(string str)
{
bool ret = str.Length > 0;
int hasPoint = 0;
foreach(char c in str) {
ret = ret && (char.IsDigit(c) || (c == '.' && hasPoint++ == 0));
}
return ret;
}
Note that this will fail if your string contains more than 2^32 '.' :D