Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you round off decimal places in C++?

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.

like image 740
Arminium Avatar asked Aug 24 '12 05:08

Arminium


People also ask

How do you round off in C?

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 “.

Does float round off in C?

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.


2 Answers

There's another solution which doesn't require casting to int:

#include <cmath>

y = floor(x * 10d) / 10d
like image 138
mimicocotopus Avatar answered Sep 23 '22 17:09

mimicocotopus


#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
}
like image 33
Jesse Good Avatar answered Sep 24 '22 17:09

Jesse Good