Daniel GIbson
Daniel GIbson

Reputation: 33

A loss of precision

If I have a double string which is equal to "123.546123" and convert it to a double with atof, I get only 123.546. What can I do to fix this?

Here is my code:

#include <iostream>

int main(){

    std::string a = "123.546123";
    double b = atof(a.c_str());

    std::cout << a << std::endl;
    std::cout << b << std::endl;

    return EXIT_SUCCESS;
}

Upvotes: 1

Views: 399

Answers (1)

flogram_dev
flogram_dev

Reputation: 42858

std::cout prints floating-point values with a precision of 6 by default. To increase that precision, use std::setprecision from <iomanip>, e.g.:

std::cout << std::setprecision(9) << b << std::endl;

Upvotes: 7

Related Questions