26

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
}
2
  • If that's supposed to be C++ you mean "bool", "true" and "false" and not "BOOL" etc.
    – siukurnin
    Jan 15, 2009 at 16:27
  • 1
    He's probably using Windows APIs, ... Jan 15, 2009 at 18:41

19 Answers 19

38

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(); 
}
11
  • 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
    Jan 15, 2009 at 16:00
  • Thanks, I fixed that and one other bug I found. Jan 15, 2009 at 16:16
  • 1
    Awesome, we're designing isFloat by committee. :) Jan 15, 2009 at 16:30
  • 1
    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... :) Jan 15, 2009 at 16:51
  • 1
    @macrocosme Why shouldn't it be? float f = 256; compiles, doesn't it? Nov 9, 2015 at 13:17
12

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

bool isFloat(const 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.

3
  • 7
    please don't use exceptions as a flow-of-control mechanism
    – Ferruccio
    Jan 15, 2009 at 16:32
  • 3
    He's not using exceptions for flow-of-control. He's catching a vexing exception ( blogs.msdn.com/ericlippert/archive/2008/09/10/… ). Jan 15, 2009 at 18:44
  • It's not a "vexing" but a "boneheaded" exception. Checking !iss.fail is correct, see Bill the Lizard above.
    – MSalters
    Jan 16, 2009 at 11:33
7

Inspired by this answer I modified the function to check if a string is a floating point number. It won't require boost & doesn't relies on stringstreams failbit - it's just plain parsing.

static bool isFloatNumber(const std::string& string){
    std::string::const_iterator it = string.begin();
    bool decimalPoint = false;
    int minSize = 0;
    if(string.size()>0 && (string[0] == '-' || string[0] == '+')){
      it++;
      minSize++;
    }
    while(it != string.end()){
      if(*it == '.'){
        if(!decimalPoint) decimalPoint = true;
        else break;
      }else if(!std::isdigit(*it) && ((*it!='f') || it+1 != string.end() || !decimalPoint)){
        break;
      }
      ++it;
    }
    return string.size()>minSize && it == string.end();
  }

I.e.

1
2.
3.10000
4.2f
-5.3f
+6.2f

is recognized by this function correctly as float.

1.0.0
2f
2.0f1

Are examples for not-valid floats. If you don't want to recognize floating point numbers in the format X.XXf, just remove the condition:

&& ((*it!='f') || it+1 != string.end() || !decimalPoint)

from line 9. And if you don't want to recognize numbers without '.' as float (i.e. not '1', only '1.', '1.0', '1.0f'...) then you can change the last line to:

return string.size()>minSize && it == string.end() && decimalPoint;

However: There are plenty good reasons to use either boost's lexical_cast or the solution using stringstreams rather than this 'ugly function'. But It gives me more control over what kind of formats exactly I want to recognize as floating point numbers (i.e. maximum digits after decimal point...).

1
  • However this is still not correct - both nan and +inf, inf, -inf should be specifiable too as they are valid floating point numbers as per IEEE standard. Oct 18, 2018 at 11:46
5

I recently wrote a function to check whether a string is a number or not. This number can be an Integer or Float.

You can twist my code and add some unit tests.

bool isNumber(string s)
{
    std::size_t char_pos(0);

    // skip the whilespaces
    char_pos = s.find_first_not_of(' ');
    if (char_pos == s.size()) return false;


    // check the significand
    if (s[char_pos] == '+' || s[char_pos] == '-') ++char_pos; // skip the sign if exist

    int n_nm, n_pt;
    for (n_nm = 0, n_pt = 0; std::isdigit(s[char_pos]) || s[char_pos] == '.'; ++char_pos) {
        s[char_pos] == '.' ? ++n_pt : ++n_nm;
    }
    if (n_pt>1 || n_nm<1) // no more than one point, at least one digit
        return false;

    // skip the trailing whitespaces
    while (s[char_pos] == ' ') {
        ++ char_pos;
    }

    return char_pos == s.size();  // must reach the ending 0 of the string
}


void UnitTest() {
    double num = std::stod("825FB7FC8CAF4342");
    string num_str = std::to_string(num);

    // Not number
    assert(!isNumber("1a23"));
    assert(!isNumber("3.7.1"));
    assert(!isNumber("825FB7FC8CAF4342"));
    assert(!isNumber(" + 23.24"));
    assert(!isNumber(" - 23.24"));

    // Is number
    assert(isNumber("123"));
    assert(isNumber("3.7"));
    assert(isNumber("+23.7"));
    assert(isNumber("  -423.789"));
    assert(isNumber("  -423.789    "));
}
4

I always liked strtof since it lets you specify an end pointer.

bool isFloat(const std::string& str)
{
    char* ptr;
    strtof(str.c_str(), &ptr);
    return (*ptr) == '\0';
}

This works because the end pointer points to the character where the parse started to fail, therefore if it points to a nul-terminator, then the whole string was parsed as a float.

I'm surprised no one mentioned this method in the 10 years this question has been around, I suppose because it is more of a C-Style way of doing it. However, it is still perfectly valid in C++, and more elegant than any stream solutions. Also, it works with "+inf" "-inf" and so on, and ignores leading whitespace.

EDIT

Don't be caught out by empty strings, otherwise the end pointer will be on the nul-termination (and therefore return true). The above code should be:

bool isFloat(const std::string& str)
{
    if (str.empty())
        return false;

    char* ptr;
    strtof(str.c_str(), &ptr);
    return (*ptr) == '\0';
}
3

[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.

3

Quick and dirty solution using std::stof:

bool isFloat(const std::string& s) {
    try {
        std::stof(s);
        return true;
    } catch(...) {
        return false;
    }
}
1
  • 1233.33.33 is not a float number. It is invalid.
    – rashedcs
    Nov 2, 2017 at 6:28
2

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.

2

With C++17:

bool isNumeric(std::string_view s)
{
    double val;
    auto [p, ec] = std::from_chars(s.data(), s.data() + s.size(), val);
    return ec == std::errc() && p == s.data() + s.size();
}

Both checks on return are necessary. The first checks that there are no overflow or other errors. The second checks that the entire string was read.

1

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.

1
int isFloat(char *s){
  if(*s == '-' || *s == '+'){
    if(!isdigit(*++s)) return 0;
  }
  if(!isdigit(*s)){return 0;}
  while(isdigit(*s)) s++;
  if(*s == '.'){
    if(!isdigit(*++s)) return 0;
  }
  while(isdigit(*s)) s++;
  if(*s == 'e' || *s == 'E'){
    s++;
    if(*s == '+' || *s == '-'){
        s++;
        if(!isdigit(*s)) return 0;
    }else if(!isdigit(*s)){
        return 0;
    }
  }
  while(isdigit(*s)) s++;
  if(*s == '\0') return 1;
  return 0;
}
1

The main issue with other responses is performance

Often you don't need every corner case, for example maybe nan and -/+ inf, are not as important to cover as having speed. Maybe you don't need to handle 1.0E+03 notation. You just want a fast way to parse strings to numbers.

Here is a simple, pure std::string way, that's not very fast:

size_t npos = word.find_first_not_of ( ".+-0123456789" );
if ( npos == std::string::npos ) {
   val = atof ( word.c_str() );
}

This is slow because it is O(k*13), checking each char against 0 thur 9

Here is a faster way:

bool isNum = true;
int st = 0;
while (word.at(st)==32) st++;    // leading spaces
ch = word.at(st);
if (ch == 43 || ch==45 ) st++;   // check +, -

for (int n = st; n < word.length(); n++) {
  char ch = word.at(n);
  if ( ch < 48 || ch > 57 || ch != 46 ) {
     isNum = false;
     break;   // not a num, early terminate
  } 
}

This has the benefit of terminating early if any non-numerical character is found, and it checks by range rather than every number digit (0-9). So the average compares is 3x per char, O(k*3), with early termination.

Notice this technique is very similar to the actual one used in the stdlib 'atof' function: http://www.beedub.com/Sprite093/src/lib/c/stdlib/atof.c

0

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

1
  • 1
    No, it doesn't, since it fails for something like "0.0". Look up strtod(), which can be used that way. Jan 15, 2009 at 16:22
0

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.

0

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;
0

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).

0

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 
} 
0

Here is a quick function which supports scientific notation. It's not the prettiest, but it works.

bool IsFloat(const char* str, unsigned int maxLen = -1)
{
    bool sawD = false;  //decimal
    bool sawE = false;  //exponent
    bool sawES = false; //exponent sign
    int i = 0;

    while (i < maxLen)
    {
        char c = str[i];
        if (c < '0' || c > '9')
        {
            if (!sawD && !sawES && !sawE && c == '.') {
                sawD = true;
            }
            else if (!sawES && !sawE && c == 'e' || c == 'E') {
                sawE = true;
            }
            else if ((i == 0 || !sawES) && c == '+' || c == '-') {
                if (i != 0)
                    sawES = true;
            }
            else if (c == 0) {
                return true;
            }
            else {
                return false;
            }
        }
        i++;
    }
    return true;
}

I raced (almost) every function on the page. Each function was ran through a loop 1 million times, comparing 21 different strings each loop. String list is below. I also included a truth table to show what each function resulted with. Blank is true, x is false.

I found it pretty interesting how each function performed so differently. Really goes to show how using the std::string functions can really slow your code down. And also how brutally slow try catch is, Emil's function took a whopping 17.7 minutes to complete!

User Time(ms) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Me 427 x x x x x x x x
Hayashi 3062 x x x x x x x x
ramakarl 24003 x x x x x x x x x x x x x x x x x x x x x
j_random 108702 x x x x x x x x
nedb 7313 x x x x x x x x
yang 31649 x x x x x x x x x x x
constantin 52918 x x x x x x x x x x x
bill the liz 108558 x x x x x x x x
Robben 112998 x x x x x x x x
Emil 17.7 min x x x

String List

  1. 10.1
  2. -10.1
  3. 0.11
  4. -0.11
  5. 0.0
  6. -0.0
  7. 0
  8. -0
  9. 10
  10. -10
  11. 10.11e-10
  12. -10.11e-10
  13. 10.11e+10
  14. Hello Float
  15. Hello1234
  16. Hello10.11
  17. 1234Hello
  18. 1234 Hello
  19. 10.11Hello
  20. 10.11 Hello
  21. 10.1.0
-1

I was looking for something similar, found a much simpler answer than any I've seen (Although is for floats VS. ints, would still require a typecast from string)

bool is_float(float val){
    if(val != floor(val)){
        return true;
    }
    else
        return false;
}

or:

auto lambda_isFloat = [](float val) {return (val != floor(val)); };

Hope this helps !

ZMazz

2
  • From the question: determine if a STRING value "qualifies" as a floating-point number
    – Ben Voigt
    Feb 24, 2020 at 17:30
  • I'm aware, nonetheless most comparisons are between ints and floats to avoid overflow -- the question is already answered w Boost. I'll qualify my description of it, though I assumed it was obvious.
    – Zach Oakes
    Feb 26, 2020 at 12:26

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.