javier santisteban
javier santisteban

Reputation: 11

My double is rounding up the decimals and I don't want it to

I converted a string to a double using ::atof, it converts OK but it rounds up the decimal and I don't want it to.

string n;
double p;

cout << "String? :" << endl;
cin >> n

p = ::atof(n.c_str());
cout << p << endl;

I usually type in numbers like 123,456.78, 12,345.87, 123,456,789.12. When I type in a smaller number like 1,234.83 or bigger the programs starts messing with the decimals.

It would be of huge help if anybody helps. Thanks!

Upvotes: 0

Views: 85

Answers (1)

Chimera
Chimera

Reputation: 6018

You need to set the precision used when sending data to the output stream using setprecision as shown below.

Of course the problem with this code is that atof() isn't your best option. However, to answer your question the use of atof() doesn't matter.

#include <iomanip>  
#include <iostream>  
#include <string>

int main()
{
    double x;
    std::string n;

    std::cout << "String? :" << std::endl;
    std::cin >> n;

    x = ::atof(n.c_str());
    std::cout << std::setprecision(10) << x << std::endl;
}

To convert and catch conversion errors you could use the following:

try
{
    x = std::stod(n);
}
catch(std::invalid_argument)
{
    // can't convert
}

Upvotes: 1

Related Questions