Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make "std::cout << 123456789.12" print "123456789.12"?

Tags:

c++

decimal

cout

How do I make

std::cout << 123456789.12

print this:

123456789.12

It always prints this:

1.23457e+008

I know that I have to play with the flags, but I cant quite figure out the right combination. If I set the fixed flag, it prints

123456789.120000
like image 306
Christian Avatar asked Mar 13 '14 15:03

Christian


2 Answers

How to ... ?

One way :-

#include <iostream>
#include <iomanip>

int main() {
    double f =123456789.12;
    std::cout << std::fixed << std::setprecision(2) << f << '\n';
    return 0;
}

See here

Please look for appropriate references

like image 153
P0W Avatar answered Sep 21 '22 19:09

P0W


You can use:

#include <iostream>
#include <limits>
using namespace std;

int main() {
    double c = 123456789.12;
    cout.precision(numeric_limits<double>::digits10 + 1);
    cout << c << endl;

    return 0;
}

Basically the limits package has traits for all the build-in types. One of the traits for floating point numbers (float/double/long double) is the digits10 attribute. This defines the accuracy of a floating point number in base 10.

See it live: http://ideone.com/Ity9m7


To read on, check out another similar question: How do I print a double value with full precision using cout?

like image 39
herohuyongtao Avatar answered Sep 17 '22 19:09

herohuyongtao