Search code examples
c++stringdoubledouble-precision

Control the precision displayed for doubles


Is theres a simple way in c++ to increase the precision of a double that is even:

For instance

 double d = 3.6

would be

d = 3.600 (adding 2 zeros)

this d is then sent to a string-class

std::to_string(d);

You may ask why? I am using a GUI (gtkmm) and in the textview every number produced has to have the same length.

This is the result if the length is not the same:

4.396       3.957       11
4.183       3.783       10
3.959       3.6     9
3.723       3.404       8
3.474       3.194       7
3.207       2.967       6
2.919       2.719       5

Is it possible to increase the decimals - that is adding extra zeros when the value is a primitive, or do I have to manipulate the string afterwards instead?

EDIT: I should have been more clear - I am not interested in std::cout . The output abow represent a GUI


Solution

  • Technically you are not changing the precision of the type double. To add "extra zeros" if the number is too short, you can use std::stringstream as follows:

    std::stringstream s;
    double d = 3.6;
    s << std::fixed << std::setprecision(3) << d;
    std::string res = s.str();
    std::cout << res;
    

    Live demo

    The above will set the digit precision to 3 digits and print 3.600.