0

I need to have my cout have two digits after the decimal point, i.e.:

the value: 2.3 to become: 2.30. I have found some solutions using iomanip, etc.

However I need a simple way to do this with only iostream.

centage = (abc/ cdf)*100;
cout << "total is "<<abc<<" of "<<cdf<<", or "<<centage <<"%";
Ziezi
  • 6,375
  • 3
  • 39
  • 49
Bardi
  • 25
  • 6
  • 2
    `cout << setprecision (2) << fixed << centage;` – erip Aug 31 '15 at 23:03
  • possible duplicate of [How do I print a double value with full precision using cout?](http://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout) – 7VoltCrayon Aug 31 '15 at 23:04
  • @erip Requires iomanip and OP seems to really want to make things hard on themselves. – user4581301 Aug 31 '15 at 23:06
  • @user4581301 Eep! Didn't see the "no iomanip" part. – erip Aug 31 '15 at 23:08
  • No worries, @erip . You have the right solution. OP wants simple, but pulls out the tools that make it anything but hard. All I can come up with is some god awful kludge like this `std::cout << (int)val << '.' << (int)(val *10 + .05) %10 << (int)(val *100 + .05) %10 << std::endl;` – user4581301 Aug 31 '15 at 23:20
  • Quick reality check, Bardi. Any reason why iomanip is off the table or is this just an exercise in masochism? – user4581301 Aug 31 '15 at 23:25
  • @user4581301 I was thinking about converting to a string and basically doing that, too. – erip Aug 31 '15 at 23:30

3 Answers3

3

The std::setprecision() manipulator is just convenience for setting the precision together with other outputs. You can set the precision directly on the stream, too:

std::cout.precision(2);
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
2

Just use stream manipulators:

cout << setprecision(2) << fixed << centage;

Which will display 2 digits after the decimal point, as in fixed notation the manipulator setprecision() specifies the number of the digits after the decimal point.

I doubt that iostream alone provides directly the facilities to temper with decimal precision. So, in my opinion there is no simpler way besides the already provided manipulators.

The other unorthodox solution is to do something using string manipulation, where for example you can convert to string and concatenate some (meaningless) 0's till you get the wanted "precision" and return the result as string.

Ziezi
  • 6,375
  • 3
  • 39
  • 49
0

here you use only iostream, but instead of cout use printf like that:

printf("%.2f\n", centage);
Ghooo
  • 496
  • 1
  • 3
  • 11