Arminium
Arminium

Reputation: 401

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.

Upvotes: 5

Views: 24190

Answers (3)

Jesse Good
Jesse Good

Reputation: 52365

#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
}

Upvotes: 8

mimicocotopus
mimicocotopus

Reputation: 5610

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

#include <cmath>

y = floor(x * 10d) / 10d

Upvotes: 10

alvmed
alvmed

Reputation: 156

You can do this:

int main()
{

    float a = 4212.12345f;
    float b = a * 10.0f;
    float c = ((int)b) / 10.0f;

    cout << c << endl;
    return 0;
}

Upvotes: 0

Related Questions