Simple Way To Round Numbers In C++

Feb 18, 2015 12:39 · 277 words · 2 minute read C++

This program prompts the user to input a decimal number and outs the number rounded to the nearest integer. Since there is no one function that will do this automatically this simple mathematical trick will round the number. Simply by adding 0.5 to the decimal number it will round up. For example, in the code below I did this by using int(round + 0.5) to accomplish this.

Example Output

Test 1
Enter a number with a decimal to round: 12
The rounded number for 12 is 12
Press any key to continue . . .

Test 2
Enter a number with a decimal to round: 12.3
The rounded number for 12.3 is 12
Press any key to continue . . .

Test 3
Enter a number with a decimal to round: 12.5
The rounded number for 12.5 is 13
Press any key to continue . . .

Test 4
Enter a number with a decimal to round: 12.8
The rounded number for 12.8 is 13
Press any key to continue . . .

Source Code

/*
 * This is a program will round a number up or down based on users input.
 * By: Jesse
 * Created 01/12/2015
 */
 
#include <iostream>
 
using namespace std;
 
int main() {
    // Declare the round variable
    //
    double round = 0.0;
 
    // Requests the user to input a decimal number to be rounded
    //
    cout << "Enter a number with a decimal to round: ";
    cin >> round;
 
    // Calculates the rounded number and outputs the number
    //
    cout << "The rounded number for " << round << " is " << int(round + 0.5) << endl;
    
    system("pause");
    return (0);
}