How do you round off decimal places in C++?
23,235
Solution 1
There's another solution which doesn't require casting to int:
#include <cmath>
y = floor(x * 10d) / 10d
Solution 2
#include <cmath>
int main() {
float f1 = 3.14159f;
float f2 = 3.49321f;
std::cout << std::floor(f1 * 10 + 0.5) / 10 << std::endl;
std::cout << std::floor(f2 * 10 + 0.5) / 10 << std::endl;
std::cout << std::round(f1 * 10) / 10 << std::endl; // C++11
std::cout << std::round(f2 * 10) / 10 << std::endl; // C++11
}
Author by
Arminium
Updated on October 19, 2020Comments
-
Arminium over 3 years
I need help rounding off a float value to one decimal place.
I know
setprecision(x)
andcout << precision(x)
. Both of which work if I wanted to round the entire float, but I am only interested in rounding the decimals to the tenths place.