std::string to float or double
std::string num = "0.6";
double temp = ::atof(num.c_str());
Does it for me, it is a valid C++ syntax to convert a string to a double.
You can do it with the stringstream or boost::lexical_cast but those come with a performance penalty.
Ahaha you have a Qt project ...
QString winOpacity("0.6");
double temp = winOpacity.toDouble();
Extra note:
If the input data is a const char*
, QByteArray::toDouble
will be faster.
std::string to float (via std::stof) precision
Floating point types are not good for holding money values. If you're content with rounding to the cent, and storing money as an integer number of cents (which is one of the simplest solutions), you could do this:
long numCents = static_cast<long>(100 * std::stof(money))
This will do "truncating" rounding, which always rounds down. If you'd like to do rounding "to the nearest cent", try:
long numCents = static_cast<long>(100 * std::stof(money) + 0.5)
As others mentioned, you may want to go for a fixed point or decimal library instead of something this simple.
Converting Input string to float/double C++
Take a look at atof. Note that atof takes cstrings, not the string class.
#include <iostream>
#include <stdlib.h> // atof
using namespace std;
int main() {
string input;
cout << "enter number: ";
cin >> input;
double result;
result = atof(input.c_str());
cout << "You entered " << result << endl;
return 0;
}
http://www.cplusplus.com/reference/cstdlib/atof/
How to convert string to float in cpp
Use std::stod
for such operations if you have access to C++11.
Otherwise use std::stringstream
as in the following:
double f = 0.0;
std::stringstream ss;
std::string s = "213.1415";
ss << s;
ss >> f; //f now contains the converted string into a double
cout << f;
Of course in both cases you have to deal with the fact the such conversion might fail for instance if you try to call stod
with "blablabla" as input.
The two methods that I suggested deal with this scenario in two different ways:
stod
throws an exception that you can catchsstream
sets a flag that you can query usingbool ss.good()
.good
will return true is the conversion was successful, false otherwise.
Is it safe to assume that float or double NaNs will always be nan as a string?
std::to_string is defined in terms of std::sprintf, which C++ adopts from the C99 standard library. And there it says:
Not-a-number is converted to
nan
ornan(char_sequence)
. Which one is used is implementation defined.
So the string will begin with nan
, but there could be other characters after it.
Unfortunately, Microsoft's library doesn't seem to be compliant. See this answer:
https://stackoverflow.com/a/7478290/856199
So, after taking all that in, the end result is that your C standard library is not C99-compliant, since 1.#QNAN is not a valid output of fprintf according to the above. But, it's well-known that Microsoft's C runtime is not C99-compliant, and it doesn't plan to become compliant any time soon, as far as I'm aware.
(Off-topic)
Don't use std::endl
, unless you really want a short form of '\n' << std::flush
.
String to Float with Precision in C++?
You are just using the wrong function.
The behavior of atoi
is described by its name itself: ascii to integer. That's why your input is truncated to its integer part, before being assigned to the float
variable.
What you need is std::atof
, instead: ascii to float.
Related Topics
Overloading Member Access Operators -≫, .*
Libpng Warning: Iccp: Known Incorrect Srgb Profile
Catching Access Violation Exceptions
Is Main() Really Start of a C++ Program
How to Create Directory Tree in C++/Linux
Why Are References Not Reseatable in C++
How to Find the Index of Current Object in Range-Based For Loop
A Std::Map That Keep Track of the Order of Insertion
How to Combine Hash Values in C++0X
Default Value to a Parameter While Passing by Reference in C++
What Is the Meaning of the Term "Free Function" in C++
What Are the Correct Link Options to Use Std::Thread in Gcc Under Linux
Pre-2016 Valgrind: Memory Still Reachable With Trivial Program Using ≪Iostream≫
Differences Between C++ String == and Compare()
"Invalid Use of Incomplete Type" Error With Partial Template Specialization