I need to write a simple program, which would round off double number to just 2 decimal places. Example: input - 0.3333333, 124.132001 output - 0.33, 124.13
Asked
Active
Viewed 318 times
-4
-
[`
`](https://en.cppreference.com/w/cpp/header/iomanip) has what you want. – sweenish Mar 14 '22 at 18:31 -
How are you outputting numbers now? `printf` or `cout` or something more exotic? – Ben Voigt Mar 14 '22 at 18:31
-
`cout << fixed << setprecision(2) << 0.3333333 << "\n";` – Eljay Mar 14 '22 at 18:35
-
Try this: [`std::set_precision`](https://en.cppreference.com/w/cpp/io/manip/setprecision) – Thomas Matthews Mar 14 '22 at 18:35
-
Question is, did OP meant to print rounded value (note, it always will be rounded down) or to actually round off. The latter is non-trivial and in certain context requires ditching floating point values as a type. – Swift - Friday Pie Mar 15 '22 at 07:26
1 Answers
0
Use std::set_precision as in
std::cout << std::fixed << std::setprecision(2) << 0.3333333;

Goswin von Brederlow
- 11,875
- 2
- 24
- 42