Reputation: 23
I am trying to convert a string
decimal number into a double
, however when I use the atof()
function, my number ends up rounding to the whole number.
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
string num = "135427.7000";
double r = atof(num.c_str());
cout << r << endl;
}
The output is:
135428
I want:
135427.7
Upvotes: 2
Views: 98
Reputation: 23792
cout
does that, not atof()
.
More precisely, operator<<
, which inserts the formated data into the std::ostream
.
You can use std::setprecision()
from the <iomanip>
standard library to print the decimals:
cout << setprecision(7) << r << endl;
or
cout << fixed << setprecision(1) << r << endl;
If you want to print the whole 135427.7000
:
cout << fixed << setprecision(4) << r << endl;
Upvotes: 7