Jump to content
  • Advertisement
Sign in to follow this  
Roof Top Pew Wee

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

This topic is 4815 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!