I need help rounding off a float value to one decimal place.
I know setprecision(x)
and cout << 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.
The round( ) function in the C programming language provides the integer value that is nearest to the float, the double or long double type argument passed to it. If the decimal number is between “1 and. 5′′, it gives an integer number less than the argument. If the decimal number is between “.
round( ) function in C returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from ”. 1 to . 5″, it returns integer value less than the argument.
There's another solution which doesn't require casting to int:
#include <cmath>
y = floor(x * 10d) / 10d
#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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With