Sign in to follow this  

[.net] Testing to see if a string can parse into a float without using exceptions.

This topic is 4601 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

The subject basically explains it all. I have a program that reads some text. If the text can be parsed as a float, then the text is thrown in a float, and the program proceeds from there. Otherwise, the text is thrown in a string, and different code is executed. Is there a standard method to check a string to see if there are characters besides numbers, '.', and '-'? Seems like it would be something common. --Vic--

Share this post


Link to post
Share on other sites
How about:


bool CheckFloat( char *string )
{
int index = 0;
while ( index < strlen( string ) )
{
if ( !is_alnum( string[index] ) && string[index] != '.' )
{
return false;
}
index++;
}
return true;
}




That all depends on the existence of a is_alnum() function, I'm pretty sure ANSI C has one defined somewhere...

Hope it helps!

[edit] Oh, use std::string instead of char * whenever you can, the function should still work for std::string strings.

Share this post


Link to post
Share on other sites

double d;
bool b = double.TryParse(mystring, NumberStyles.Float, System.Globalization.CultureInfo.CurrentCulture.NumberFormat, out result);
if(!b) {
...
}


Share this post


Link to post
Share on other sites
Actually, float also has a TryParse... But in .NET 2.0 (for both float and double).

If you're working with .NET 1.1, I think the best way (though not perfect), would be to check against a regular expression matching something like:
(+|-)?[0-9]*(.[0-9]*)?([eE](+|-)?[0-9]*)?

But as I said, it's not perfect: It doesn't accept some characters your local settings would (maybe thousands seperators), and it doesn't check for overflows and such.

Share this post


Link to post
Share on other sites
No reason not to use doubles. He can always cast to a float later if it matters. The regular expression version, however, is culture specific and thus makes the code a lot harder to port.

Share this post


Link to post
Share on other sites

This topic is 4601 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this