+ 2

How can I round a double number in c++?

Hi. How can I round a number in c++? I'm using this code: round(double * 100) / 100; It works correctly. But sometimes I don't want this result. for example, sometimes the number has just 1 decimal digit (example: 1.8) and I want to see the result as 1.80. How can I do this?

6th Mar 2018, 1:27 PM
Amir Hossein
Amir Hossein - avatar
2 Antworten
+ 2
You have to first set the output as fixed, then set the precision to 2 decimal places. Something like this: double var = round(double * 100) / 100; std::cout << std::fixed << std::setprecision(2) << var; Unfortunately, it only works on the output stream. If you need the value for another computation, I don't know of any other way currently.
6th Mar 2018, 1:43 PM
apex137
apex137 - avatar
+ 2
@nik1082 I don't think he can force the computer to calculate something using 1.80 as the computer will omit the zero in its calculations automatically. So it must be for output itself.
6th Mar 2018, 3:24 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar