views:

1638

answers:

11

Does anybody know of a convenient means of determining if a string value "qualifies" as a floating-point number.

BOOL IsFloat( string MyString ) { ... etc ...

return ... // TRUE if float; FALSE otherwise }

Thanks in anticipation.

A: 

You could use atof and then have special handling for 0.0, but I don't think that counts as a particularly good solution.

Douglas Leeder
No, it doesn't, since it fails for something like "0.0". Look up strtod(), which can be used that way.
David Thornley
A: 

Compare this thread for a java implementation - there's a regex solution that will match as well as a number of java specific answers that could be done similarly in C++.

plinth
+2  A: 

I'd imagine you'd want to run a regex match on the input string. I'd think it may be fairly complicated to test all the edge cases.

This site has some good info on it. If you just want to skip to the end it says: ^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$

Which basically makes sense if you understand regex syntax.

Greg Rogers
A: 

This is a common question on SO. Look at this question for suggestions (that question discusses string->int, but the approaches are the same).

Note: to know if the string can be converted, you basically have to do the conversion to check for things like over/underflow.

Mr Fooz
+10  A: 

You may like Boost's lexical_cast (see http://www.boost.org/doc/libs/1_37_0/libs/conversion/lexical_cast.htm).

bool isFloat(std::string someString)
{
  using boost::lexical_cast;
  using boost::bad_lexical_cast; 

  try
  {
    boost::lexical_cast<float>(someString);
  }
  catch (bad_lexical_cast &)
  {
    return false;
  }

  return true;
}

You can use istream to avoid needing Boost, but frankly, Boost is just too good to leave out.

Adam Wright
please don't use exceptions as a flow-of-control mechanism
Ferruccio
He's not using exceptions for flow-of-control. He's catching a vexing exception ( http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx ).
Max Lybbert
It's not a "vexing" but a "boneheaded" exception. Checking !iss.fail is correct, see Bill the Lizard above.
MSalters
+2  A: 

[EDIT: Fixed to forbid initial whitespace and trailing nonsense.]

#include <sstream>

bool isFloat(string s) {
    istringstream iss(s);
    float dummy;
    iss >> noskipws >> dummy;
    return iss && iss.eof();     // Result converted to bool
}

You could easily turn this into a function templated on a type T instead of float. This is essentially what Boost's lexical_cast does.

j_random_hacker
+12  A: 

If you can't use a Boost library function, you can write your own isFloat function like this.

#include <string>
#include <sstream>

bool isFloat( string myString ) {
    std::istringstream iss(myString);
    float f;
    iss >> noskipws >> f; // noskipws considers leading whitespace invalid
    // Check the entire string was consumed and if either failbit or badbit is set
    return iss.eof() && !iss.fail(); 
}
Bill the Lizard
This (and all the duplicate solutions) will not work on "3.14 hello". You have draing the stream to make sure the number is not followed by any non-whitespace.
Dave Ray
Thanks, I fixed that and one other bug I found.
Bill the Lizard
Don't forget to forbid initial whitespace with noskipws.
j_random_hacker
Awesome, we're designing isFloat by committee. :)
Bill the Lizard
Fair enough... In that case I think it needs some sort of "hump" for food and water storage over long periods, in case of drought... :)
j_random_hacker
Nice. "A camel is a horse designed by a committee," for anyone who doesn't get the reference. I just happened to have http://blogs.msdn.com/mikechampion/archive/2006/12/21/the-json-vs-xml-debate-begins-in-earnest.aspx open in another tab. :)
Bill the Lizard
This does the job. Thanks.
AndyUK
A: 

What you could do is use an istringstream and return true/false based on the result of the stream operation. Something like this (warning - I haven't even compiled the code, it's a guideline only):

float potential_float_value;
std::istringstream could_be_a_float(MyString)
could_be_a_float >> potential_float_value;

return could_be_a_float.fail() ? false : true;
Timo Geusch
A: 

it depends on the level of trust, you need and where the input data comes from. If the data comes from a user, you have to be more careful, as compared to imported table data, where you already know that all items are either integers or floats and only thats what you need to differentiate.

For example, one of the fastest versions, would simply check for the presence of "." and "eE" in it. But then, you may want to look if the rest is being all digits. Skip whitespace at the beginning - but not in the middle, check for a single "." "eE" etc.

Thus, the q&d fast hack will probably lead to a more sophisticated regEx-like (either call it or scan it yourself) approach. But then, how do you know, that the result - although looking like a float - can really be represented in your machine (i.e. try 1.2345678901234567890e1234567890). Of course, you can make a regEx with "up-to-N" digits in the mantissa/exponent, but thats machine/OS/compiler or whatever specific, sometimes.

So, in the end, to be sure, you probably have to call for the underlying system's conversion and see what you get (exception, infinity or NAN).

blabla999
+1  A: 

You can use the methods described in How can I convert string to double in C++?, and instead of throwing a conversion_error, return false (indicating the string does not represent a float), and true otherwise.

strager
A: 

I would be tempted to ignore leading whitespaces as that is what the atof function does also:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals, and interprets them as a numerical value. The rest of the string after the last valid character is ignored and has no effect on the behavior of this function.

So to match this we would:

bool isFloat(string s) 
{ 
    istringstream iss(s); 
    float dummy; 
    iss >> skipws >> dummy; 
    return (iss && iss.eof() );     // Result converted to bool 
} 
David Relihan