C++ round a double up to 2 decimal places

Bryce Hahn picture Bryce Hahn · Sep 19, 2014 · Viewed 57.6k times · Source

I am having trouble rounding a GPA double to 2 decimal places. (ex of a GPA needed to be rounded: 3.67924) I am currently using ceil to round up, but it currently outputs it as a whole number (368)

here is what I have right now

if (cin >> gpa) {
    if (gpa >= 0 && gpa <= 5) {
           // valid number

           gpa = ceil(gpa * 100);

           break;
    } else {
           cout << "Please enter a valid GPA (0.00 - 5.00)" << endl;
           cout << "GPA: ";

    }
}

using the above code with 3.67924 would output 368 (which is what I want, but just without the period between the whole number and the decimals). How can I fix this?

Answer

kaveish picture kaveish · Aug 12, 2019

To round a double up to 2 decimal places, you can use:

#include <iostream>
#include <cmath>

int main() {
    double value = 0.123;
    value = std::ceil(value * 100.0) / 100.0;
    std::cout << value << std::endl; // prints 0.13
    return 0;
}

To round up to n decimal places, you can use:

double round_up(double value, int decimal_places) {
    const double multiplier = std::pow(10.0, decimal_places);
    return std::ceil(value * multiplier) / multiplier;
}

This method won't be particularly fast, if performance becomes an issue you may need another solution.