• Advertisement

Archived

This topic is now archived and is closed to further replies.

String to Integer in C#

This topic is 5024 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

First of all, I have a text box where a user needs to input a number in Windows Forms. How can I check to make sure they entered a number, without spaces or characters and other garbage? Secondly, can I go any bigger than a ulong in terms of the largest unsigned integer? If so, how? Is there any way for arbitrary length? And lastly, I''ll need to convert this string "number" into an integer (my ulong, for example). I''ve tried but failed at doing this. I take it you cannot cast or do stuff like ToInt32, etc. How do I convert the text box inputted number (string) into a real number for computation? Thanks for any help you can provide on any of these issues.

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
There is a UInt64 type.

To convert string to UInt64 use the static method of the Convert object.

UInt64 uiMyNum = Convert.ToUInt64("12312312312312", 10);

HTH

Share this post


Link to post
Share on other sites
Use the on Keydown event to determine if the keycode is in the range of numeric ascii values.

private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
//allow only numbers and a decimal point and backspace key
if (CheckForNumeric(e.KeyChar) == false)
e.Handled = true ;

}


bool CheckForNumeric(char ch)
{
//allow only numbers and a decimal point and backspace key
int keyInt = (int)ch ;
if (( keyInt < 48 || keyInt > 57) && keyInt != 46 && keyInt != 8)

return false;
else
return true ;
}


That should make sure no one can enter any none numeric value. You can check the integrated types max values also

Share this post


Link to post
Share on other sites
the Decimal data type, here''s a quote from the MSDN:

The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors

and each built in type has a Parse static function for converting from strings, that throws an exception when the string doesn''t match the requirements ... and there are also things called validators, but I don''t know much about them.

Share this post


Link to post
Share on other sites
quote:
Original post by Xai
and each built in type has a Parse static function for converting from strings, that throws an exception when the string doesn''t match the requirements

There''s also a Double.TryParse, which can also be used with integers. It doesn''t throw.

quote:

and there are also things called validators, but I don''t know much about them.


Validators are only available in ASP.NET/Webforms. Maybe Winforms/Whidbey or Avalon will have them.





--
AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.
[Project site] [Blog] [RSS] [Browse the source] [IRC channel]

Share this post


Link to post
Share on other sites
Use Int32.Parse() which will throw an exception (NumberFormatException or something) if it isn''t a valid number. Catch the exception and inform user appropriately.

Mark

Share this post


Link to post
Share on other sites
Throwing and catching exceptions is quite slow and shouldn''t be used for things like checking to see if a string is numerical.

You can use regular expressions for this:

using System.Text.RegularExpressions;

class myClass
{
private static Regex regexNumber;

static myClass()
{
regexNumber = new Regex("^[0-9]+$", RegexOptions.Compiled);
}

static bool IsNumber(string text)
{
return regexNumber.IsMatch(text);
}

....
if (IsNumber(txtNumber.Text))
{
}
....
}

This regular expression checks for strings that only have ''0''..''9''. If you also want to check for a sign (+ or -), change the regex-string to "^[+\\-]?[0-9]+$".

---
tommy online: http://users.pandora.be/tommycarlier

Share this post


Link to post
Share on other sites
I normally don''t find performance to be a problem in any situation where I''m converting a number to a string. If the user supplied the string, performance does not matter much because a user cannot supply strings faster than I can check them, no matter how poor my algorithm

If I was doing something where high-performance mattered (like reading a really big text file in), I''d expect the vast majority of the entries to be valid therefore it would not throw the exception very often.

Mark

Share this post


Link to post
Share on other sites
Thanks for the replies. I got that working now.

However, I'm working in SharpDevelop, and I have created two files. I have my Main.cs file, which uses a class I built in my Secondary.cs file. I cannot figure out how to combine the two of them. It keeps telling me "are you missing a using directive or an assembly listing?". I've tried everything and failed to figure out how to combine multiple .cs files. The two files are in the combine and I tried putting them in the same namespace, etc. But I have not had any luck. How do you combine multiple .cs files, for use in my Main.cs file?

Thanks again.

Edit:

Heh, I'd rather not start new topics for all of my little questions. I have one more.

How can I output an array inside a message box or a dialog box?
Let's say I have array xyz of 10 elements. I need to do something like this:

MessageBox.Show("Your lucky numbers are: " + XYZ_ARRAY, "Lucky Drawing", ....)

I couldn't figure out how to output an entire array inside the message box. Rather it said: "Your lucky numbers are: System.Int32". Any ideas? I thought of a for loop, and outputting the numbers separately, but I don't see how that would fit into a message box function. Thanks.

[edited by - khaos on April 16, 2004 10:51:08 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by Khaos
How can I output an array inside a message box or a dialog box?
Let''s say I have array xyz of 10 elements. I need to do something like this:

MessageBox.Show("Your lucky numbers are: " + XYZ_ARRAY, "Lucky Drawing", ....)




public string ArrayToString(Array a, string separator)
{
string s
if (a.Length == 0) return "";
s = a[0].ToString();
for(int i=1; i<=a.Length; i++)
s += separator + a.ToString();
return s;
}

...

MessageBox.Show("Your lucky numbers are: " + ArrayToString(XYZ_ARRAY, ", "), ...);
// will show: Your lucky numbers are: 1, 34, 43, 8, 16


---
tommy online: http://users.pandora.be/tommycarlier

Share this post


Link to post
Share on other sites
Thank you. I tried that, and it works more towards the end I want.
Yet, when I say: MessageBox.Show("Here: " + ArrayToString(xyz, ", ") ....)
It still prints out System.Int32... etc. for all my values.
How do I specify the array inside the MessageBox function?
xyz does not work, nor does xyz[]. What will?

Share this post


Link to post
Share on other sites
The code didn't come through right: a[ i ] (without spaces) was removed and made the rest italic . Here's the corrected code:

public string ArrayToString(Array a, string separator)
{
string s;
if (a.Length == 0) return "";
s = a[0].ToString();
for(int i=1; i<=a.Length; i++)
s += separator + a[ i ].ToString();
return s;
}


---
tommy online: http://users.pandora.be/tommycarlier

[edited by - Tommy Carlier on April 16, 2004 2:23:04 PM]

[edited by - Tommy Carlier on April 16, 2004 2:24:39 PM]

Share this post


Link to post
Share on other sites
Thank you. What about combining multiple C# files? If I have Main.cs and MyClass.cs, how can I put them together?

Share this post


Link to post
Share on other sites
Just having them in the same assembly should work. If you still can''t get it to work, post both of them.

Share this post


Link to post
Share on other sites
I have MainForm.cs which initializes my class in MyClass.cs called MyClass.

// inside MyFormProject namespace
MyClass bob = new MyClass(); // in MainForm.cs

I get an error about a missing namespace or assembly listing.

And my MyClass.cs file:

// inside MyFormProject namespace?? should it be? it is now.
class MyClass
{
public void Open()
{
...
}
}

And in MainForm.cs I use this line:

bob.Open()

It all fails. Both files are in the combine together. I don''t understand. Thanks for any help again.

Share this post


Link to post
Share on other sites
I know I can''t seem to get it to work, but I''m sure someone has included multiple C# files, enough to know how to do it properly.

thanks

Share this post


Link to post
Share on other sites
quote:

I normally don''t find performance to be a problem in any situation where I''m converting a number to a string. If the user supplied the string, performance does not matter much because a user cannot supply strings faster than I can check them, no matter how poor my algorithm

If I was doing something where high-performance mattered (like reading a really big text file in), I''d expect the vast majority of the entries to be valid therefore it would not throw the exception very often.

Mark


You should never use exceptions to catch user errors--they are meant to be used when there is an error with the program.

Share this post


Link to post
Share on other sites
quote:
Original post by bytecoder
You should never use exceptions to catch user errors--they are meant to be used when there is an error with the program.

An exception is just an exceptional codepath , which is commonly used to signal sometype of error.

Also a user error, is still an error. Invalid input will normally put the system into an erroneous state if it isnt excluded, which generally means signalling an error.

Share this post


Link to post
Share on other sites

  • Advertisement