2

I'm using C++ iomanip to output double precision numbers in 2 decimal places. But I don't like getting results like -0.00 as produced in the following code:

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

  int main(){
    double x=-0.001;
    cout<<setiosflags(ios_base::fixed);
    cout<<setprecision(2)<<x<<endl;
    return 0;
  }

The results for other values of x are all correctly rounded to 2 decimal places except when -0.005<x<0, in which case the annoying -0.00 is printed instead of 0.00. The -0.00 result remains even if one does x=round(x*100)*0.01 before the cout lines using round in cmath. What manipulators can handle this correctly?

Zhuoran He
  • 873
  • 9
  • 15
  • Thanks, guys! I now understand `round(x*100)` returns `-0` of type `double`. One can do `if(x==0) x=0` after rounding or `if(abs(x)<0.005) x=0` before rounding, but there's no built-in manipulator yet that does this for us. – Zhuoran He Aug 01 '17 at 04:01

0 Answers0