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?
Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.
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.
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