C# equivalent of PHP's intval()

  • Thread starter Doesn't Work At McDonalds
  • Start date
D

Doesn't Work At McDonalds

intval() in PHP is a simple function... you toss it a string and it
gives you the integer value. If the string is all text, the value is
0. It's very nice for simple form validation where you want to force
a form value to be an integer. If the user enters one, it gets used.
If they mess around, the value becomes 0. Simple.

So, after googling for how to do this in C# with asp.net, the best I
can come up with is Convert.ToInt32() which tosses an error if the
string you feed it isn't an integer. I don't want an error. I want a
zero.

Is there a function built into C#/asp.net that's like intval()?
 
D

Doesn't Work At McDonalds

It would take you about three lines to return a zero from the function you
can write to do this. I dont believe theres a method out of the box for it.

Take a look at int32.parse also.

Regards

John Timney (MVP)http://www.johntimney.comhttp://www.johntimney.com/blog

John,

Thanks.

I wrote a quick function that uses a regex to check whether there are
any characters in the string (^[0-9]+$). If it fails the regex, it
returns 0. If not, it returns the numerical value of the string.
 
B

Ben Voigt [C++ MVP]

Doesn't Work At McDonalds said:
intval() in PHP is a simple function... you toss it a string and it
gives you the integer value. If the string is all text, the value is
0. It's very nice for simple form validation where you want to force
a form value to be an integer. If the user enters one, it gets used.
If they mess around, the value becomes 0. Simple.

So, after googling for how to do this in C# with asp.net, the best I
can come up with is Convert.ToInt32() which tosses an error if the
string you feed it isn't an integer. I don't want an error. I want a
zero.

Is there a function built into C#/asp.net that's like intval()?

string s = "ABC";
int intval;
int.TryParse(s, out intval);
 
J

Jon Skeet [C# MVP]

I wrote a quick function that uses a regex to check whether there are
any characters in the string (^[0-9]+$). If it fails the regex, it
returns 0. If not, it returns the numerical value of the string.

How does it work with:

999999999999999999999999999999999999999

?

Ben's answer (TryParse) is the best one here.

Jon
 
D

Doesn't Work At McDonalds

Thanks to Ben for the awesome answer and to Jon for weighing in behind
it. Works great!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top