2

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 ?

SadStudent
  • 287
  • 1
  • 4
  • 16

2 Answers2

1

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

Mario Rossi
  • 7,651
  • 27
  • 37
  • Sadly, this is the only solution that worked so far, but I was just sure that C++ might have something more elegant that I'm just not aware of. – SadStudent Sep 02 '13 at 09:18
  • @SadStudent Your requirement is a bit uncommon. The usual is to have a fixed number of decimal positions (and zero-filling :-( ). It's very good you asked. – Mario Rossi Sep 02 '13 at 09:21
0

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

LLenain
  • 549
  • 1
  • 7
  • 12
  • I don't see how can I solve it using those functions because at most they can help me add extra zeros for example in the end which I wrote I don't want I just want up to 5 digits after the point – SadStudent Sep 02 '13 at 07:40
  • As I mention in the example code I've tried that but then it ruins the cases where I don't want meaningless trailing zeros because it's "fixed", I'm looking for a way that does not make me check every the number of digits in every double I want to put in the stream – SadStudent Sep 02 '13 at 08:01