18

Is there a function similar to atoi which converts a string to float instead of to integer?

lital maatuk
  • 5,921
  • 20
  • 57
  • 79

11 Answers11

26

atof()

(or std::atof() talking C++ - thanks jons34yp)

Community
  • 1
  • 1
RED SOFT ADAIR
  • 12,032
  • 10
  • 54
  • 92
  • 15
    @Glen: and `atoi` converts to `long`, so what? –  Feb 16 '11 at 13:31
  • 4
    @Glen: Do you really want those 3 pages of explanation why there is no atof_float()? atof() is the correct answer to the question that solves the problem of a equivalent to atoi. The question was not: "Are there other functions to convert from strings to numeric types?". – RED SOFT ADAIR Feb 16 '11 at 13:32
  • @Vlad Lazarenko, the question was about converting a string to a float, not a double – Glen Feb 16 '11 at 13:33
  • 1
    `boost::lexical_cast` and `strtof` are both much better solutions than `atof` as `atof` has no error detection. – Zac Howland Feb 16 '11 at 13:35
  • @RED SOFT ADAIR, no, I'd like to see an accurate answer, not a "close enough that it sorta works". strtof is more correct than atof, and @larsmans lexical_cast is even more correct (provided the OP is using boost of course) – Glen Feb 16 '11 at 13:36
  • @Glen: I appreciate your correctness but it seems a little bit like overkill to me considering such a simple question. The question was for a "a function similar to atoi". – RED SOFT ADAIR Feb 16 '11 at 13:41
  • 5
    @Glen, @RED: While the question indeed asks about "float" (not `float`) in the same way it mentions "integer" (not `int`), and thus an answer using `double` should be fine, this answer is still bad, as all `atox()` functions have the built-in flaw that an erroneous string returns a valid value. And for an API function that's as bad as they come. – sbi Feb 16 '11 at 13:50
  • @RED SOFT ADAIR, the question was "Is there a function similar to atoi which converts a string to float instead of to integer?" not "Is there a function similar to atoi which converts a string to double instead of to integer?". It's onlY "a function similar to atoi" if you start ignoring the other requirements in the question. It is pedantic, but if he just wanted a function similar to atoi we could have suggested atol, atoll or atof. – Glen Feb 16 '11 at 13:50
  • 1
    `If no conversion can be performed, 0.0 is returned.` Why would anyone use a stupid function that returns 0.0 on error? 0.0 may be a valid value and that is indistinguishable from garbage input. I don't like this at all. – Kenji Nov 21 '15 at 22:10
17
boost::lexical_cast<float>(str);

This template function is included in the popular Boost collection of libraries, which you'll want learn about if you're serious about C++.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 5
    That requires the download and installation of boost (apx. 500 MB). You should note that in your answer. C++ novices will be confused otherwise. – RED SOFT ADAIR Feb 16 '11 at 13:44
  • On my system, this takes a simple `sudo apt-get libboost-dev` and maybe a minute waiting from my slow internet link. – Fred Foo Feb 16 '11 at 13:47
  • @sbi, I mostly agree, however some smart, very talented, developers may not have access to boost for lots of reasons (politics being a big one). It's not a great situation, however writing them off as "not worth their money" is a little harsh. – Glen Feb 16 '11 at 14:20
  • Oh man - i am using boost since years. I am impressed again and again that such a simple question can raise such "religious" conflicts. – RED SOFT ADAIR Feb 16 '11 at 14:20
  • @Glen: Yes, you're right, pesky company policies keep coming up as reasons not to use boost. @RED: I apologize, this was indeed a bit harsh. I have deleted my comment. – sbi Feb 16 '11 at 14:34
17

Convert a string to any type (that's default-constructible and streamable):

template< typename T >
T convert_from_string(const std::string& str)
{
  std::istringstream iss(str);
  T result;
  if( !(iss >> result) ) throw "Dude, you need error handling!";
  return result;
}
sbi
  • 219,715
  • 46
  • 258
  • 445
  • 2
    Thanks for the only C++ based solution! All other answers refer to C language, but the question is tagged C++. – Mass Nerder Feb 16 '11 at 13:52
  • 2
    @Mass: Except for [larsmans's answer](http://stackoverflow.com/questions/5017001/like-atoi-but-to-float/5017054#5017054), which is more elegant. – sbi Feb 16 '11 at 13:54
  • My compiler (gcc 4.1) asks for parenthesis around "iss>>result" – Barth Apr 04 '12 at 06:38
  • @Barth: I suppose your compiler is right. (I had typed that from memory.) It's fixed now. Thanks for pointing it out! – sbi Apr 04 '12 at 09:27
  • This is the best solution. No needless boost dependency, no C++11 features, proper error handling. Just plain code that works. Note, however, a semicolon is missing after the `throw "Dude, you need error handling!"` statement – Kenji Nov 15 '15 at 02:48
  • @Kenji: Thanks for pointing out the missing semicolon. IMO the rest of your statements are all wrong. – sbi Nov 16 '15 at 07:15
  • @sbi So it does have a boost dependency? I don't see one. It does rely on C++11? My non-11 compiler accepts this. It doesn't have proper error handling? I see clear error handling. It doesn't work? It worked for me. Ok, it being the best solution is subjective. – Kenji Nov 21 '15 at 22:03
  • 1
    @Kenji: Boost isn't needless, the error handling isn't proper, and it will not work effectively (or properly, in case of spaces) for strings.I am sure `lexical_cast<>()` got this (and more) all covered. – sbi Nov 22 '15 at 18:30
  • @sbi thanks for clarifying. But the question was about floats, not strings. Atof fails to handle errors at all (returning 0.0 on error is idiocy because 0.0 could be a perfectly valid value) What exactly is wrong with the error handling here (other than that I have to throw my own exception instead of that string)? – Kenji Nov 28 '15 at 00:07
  • 1
    @Kenji: For one, throwing string literals is a sure way to hell – and when doing this in an answer to a newbie question this may well send innocents to hell. Also, this code doesn't check if there's unconsumed non-whitespace characters left in the string, which is likely an error. And while the question was about floats, the answer converts just about anything streamable, so it should work well for just about everything. All this and more has been considered when `boost::lexical_cast` was designed and implemented. Why roll your own if it is inferior? – sbi Dec 02 '15 at 10:47
  • @sbi Okay, thanks. I've been working with this piece of code and I actually noticed this: "this code doesn't check if there's unconsumed non-whitespace characters left in the string, which is likely an error" haha. That's a good thing to check too. Why roll my own if it is inferior? To reduce dependencies. I prefer things lightweight, especially in this particular project I'm working on. – Kenji Dec 02 '15 at 12:46
  • 3
    _"Where I work, we have our own term for the Not Invented Here Syndrom."_ – sbi Dec 04 '15 at 06:21
6

strtof

From the man page

The strtod(), strtof(), and strtold() functions convert the initial portion of the string pointed to by nptr to double, float, and long double representation, respectively.

The expected form of the (initial portion of the) string is optional leading white space as recognized by isspace(3), an optional plus (‘‘+’’) or minus sign (‘‘-’’) and then either (i) a decimal number, or (ii) a hexadecimal number, or (iii) an infinity, or (iv) a NAN (not-a-number).

/man page>

atof converts a string to a double (not a float as it's name would suggest.)

Glen
  • 21,816
  • 3
  • 61
  • 76
6

As an alternative to the the already-mentioned std::strtof() and boost::lexical_cast<float>(), the new C++ standard introduced

float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);

for error-checking string to floating-point conversions. Both GCC and MSVC support them (remember to #include <string>)

Cubbi
  • 46,567
  • 13
  • 103
  • 169
1

Use atof from stdlib.h:

double atof ( const char * str );
Ferdinand Beyer
  • 64,979
  • 15
  • 154
  • 145
1

Prefer strtof(). atof() does not detect errors.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • Actually, prefer string streams, unless you know you have a performance problem. Nevertheless, `+1` from me, because it is correct and important that the `atox()` family of functions have a fatal flaw built into their interface. – sbi Feb 16 '11 at 13:43
  • Can you please provide a link about the problems with using atof()? I use it since 20 Years - i can not remember a single problem with it. – RED SOFT ADAIR Feb 17 '11 at 09:39
  • `man atof`: The `atof()` function converts the initial portion of the string pointed to by nptr to double. The behavior is the same as `strtod(nptr, (char **) NULL);` **except that `atof()` does not detect errors.** – Maxim Egorushkin Feb 17 '11 at 10:08
  • What kind of errors? I am a windows programmer. I checked http://msdn.microsoft.com/en-us/library/hc25t012%28VS.80%29.aspx, http://www.cppreference.com/wiki/string/c/atof and also http://www.cplusplus.com/reference/clibrary/cstdlib/atof/. None of these say anything about errors. Is this possibly a platform specific issue? – RED SOFT ADAIR Feb 17 '11 at 15:03
  • 1
    Oh, windows programmer, that explains it, lol. `atof()` does not detect *parsing* errors. Try `std::cout << atof("2abc123") << '\n';`. – Maxim Egorushkin Feb 17 '11 at 15:21
  • Oh, a unix-Programmer. That explains it. Don't you think that you are a little bit subjective? So i still can not see any difference between http://www.cplusplus.com/reference/clibrary/cstdlib/atof/ and http://www.cplusplus.com/reference/clibrary/cstdlib/strtod/. Both state: "If no valid conversion could be performed, or if the correct value would cause underflow, a zero value (0.0) is returned." – RED SOFT ADAIR Feb 17 '11 at 15:33
  • From http://www.cplusplus.com/reference/clibrary/cstdlib/strtod/: "A pointer to the rest of the string after the last valid character is stored in the object pointed by endptr" – Maxim Egorushkin Feb 17 '11 at 15:34
  • Aha, well i always used parsers for parsing. I use conversion functions for conversion. Thats all we were arguing about? – RED SOFT ADAIR Feb 17 '11 at 15:39
  • 1
    If the string gets corrupted between parsing and conversion `atof()` won't notice. – Maxim Egorushkin Feb 17 '11 at 15:50
1

This would also work ( but C kind of code ):

#include <iostream>

using namespace std;

int main()
{
float myFloatNumber = 0;
string inputString = "23.2445";
sscanf(inputString.c_str(), "%f", &myFloatNumber);
cout<< myFloatNumber * 100;

}

See it here: http://codepad.org/qlHe5b2k

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
0
#include <stdlib.h>
double atof(const char*);

There's also strtod.

aschepler
  • 70,891
  • 9
  • 107
  • 161
0

Try boost::spirit: fast, type-safe and very efficient:

std::string::iterator begin = input.begin();
std::string::iterator end = input.end();
using boost::spirit::float_;

float val;
boost::spirit::qi::parse(begin,end,float_,val);
Nova
  • 2,039
  • 2
  • 21
  • 16
-1

As an alternative to all above, you may use string stream. http://cplusplus.com/reference/iostream/stringstream/

Neomex
  • 1,650
  • 6
  • 24
  • 38