How do you round decimal places in C ++?

I need help rounding the float value to one decimal place.

I know setprecision(x) and cout << precision(x) . Both of them work if I wanted to get around the whole floating one, but I'm only interested in rounding decimals to tenth place.

+4
source share
3 answers

There is another solution that does not require casting for int:

 #include <cmath> y = floor(x * 10d) / 10d 
+10
source
 #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 } 
+7
source

You can do it:

 int main() { float a = 4212.12345f; float b = a * 10.0f; float c = ((int)b) / 10.0f; cout << c << endl; return 0; } 
0
source

All Articles