Question

As I understand it the setprecision function specifies the minimal precision but when I run the following code I get only 3 numbers after the decimal point:

int main()
{
    double a = 123.4567890;
    double b = 123.4000000;
    std::cout << std::setprecision(5) << a << std::endl; // Udesireble 
    std::cout.setf(std::ios::fixed);
    std::cout << std::setprecision(5) << a << std::endl; // Desireble 

    std::cout << std::setprecision(5) << b << std::endl; // Udesireble
    std::cout.unsetf(std::ios::fixed);
    std::cout << std::setprecision(5) << b << std::endl; // Desireble 
    return 0;
}

which prints:

123.46      // Udesireble
123.45679   // Desireble 
123.40000   // Udesireble
123.4       // Desireble

Is there any way I can avoid checking the number of digits after the decimal point myself in order to know whether to set fixed ?

Was it helpful?

Solution

My impression is that you will need to format to string first, and then replace trailing zeros with spaces.

OTHER TIPS

For the streams, you can use two functions. setfill(char_type c), which set the character to write, to match with the number of needed character (more information here)

There is the setw(int) function, which set the width of field of the value to display. (documentation here )

Using these functions, you may have a solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top