How to round off double value to 2 decimal places in C++

posted 8 min read

Preciseness is crucial in programming, particularly when working with numerical quantities. It's common to need to round a double to a certain number of decimal places in a variety of fields, from scientific calculation to banking. We will look into C++ and examine several techniques to round a double to two decimal places in this article. Whether you're an experienced programmer or a novice to the field, knowing this basic function is essential to producing precise and well-rounded programs. Come along as we explore different approaches and practices to help you understand details of C++ rounding.

Rounding a Double Value to 2 Decimal Places in C++

1. Using round()

Programming frequently involves rounding a double to two decimal places, particularly in mathematical or financial applications. We'll look at a simple C++ technique to do this.

  1. STEP 1: Create a double variable that holds the value you want to round.
  2. STEP 2: Multiply the double by 100 to shift the decimal two places to the right.
  3. STEP 3: Round the result using the 'round()' function from the'' library.
#include 
#include
int main() {
    // Example value to be rounded
    double value = 12.345;
    // Step 1: Multiply by 100
    double multipliedValue = value * 100;
    // Step 2: Round the result
    double roundedValue = round(multipliedValue);
    // Step 3: Divide by 100 to get the final rounded value
    roundedValue /= 100;
    // Display the result
    std::cout << "Original Value: " << value << std::endl;<br>     std::cout << "Rounded Value: " << roundedValue << std::endl;<br>     return 0;
}
  • The original number is first multiplied by 100 to shift the decimal two places to the right.
  • After that, the result is rounded to the nearest integer using the 'round()' method.
  • In order to return the decimal to its initial location and essentially round to two decimal places, we divide the result by 100.

Output:

2. Using 'std::setprecision'

Another way to round a double to two decimal places is to use the '' library's 'std::setprecision'function.

  1. STEP 1: Include the necessary header files.
  2. STEP 2: Use 'std::setprecision' to set the precision to two decimal places.
  3. STEP 3: Use 'std::fixed' to ensure that the precision is applied to the decimal part.
#include 
#include
int main() {
    // Example value to be rounded
    double value = 12.345;
    std::cout << "Original Value: " << value << std::endl;<br>     // Step 1: Set precision to two decimal places
    std::cout << std::fixed << std::setprecision(2);<br>     // Step 2: Display the rounded value
    std::cout << "Rounded Value: " << value << std::endl;<br>     return 0;
}
  • By using 'std::setprecision(2)', we specify that we want two digits after the decimal point.
  • Even in cases where trailing zeros are present, 'std::fixed' makes sure that the accuracy is applied to the decimal portion.

Output:

FAQ Q:How do these methods handle edge cases, such as extremely large or small double values?
A: The methods provided are generally robust for a wide range of double values. However, extreme values may lead to precision issues. It's advisable to test and adapt the methods based on your specific application's requirement.

Some Alternative Approches

Some alternative method used to round off the decimal values as followed:

1. Using printf()

An alternate method is to round to two decimal places by using the 'printf' function and the format specifier "%.2f".

  • STEP 1: Include the necessary header file.
  • STEP 2: Use printf with the "%.2f" format specifier
  • STEP 3: Pass the double value as an argument to printf.
#include 
int main() {
    // Example value to be rounded
    double value = 12.345;
    // Step 1: Display the rounded value using printf
    printf("Original Value: %.3f\n", value);
    printf("Rounded Value: %.2f\n", value);
    return 0;
}

The "%.2f" format specifier in 'printf' indicates that we want two digits after the decimal point.

Output:

FAQ Q: Can I round to a different number of decimal places?
A: Yes, you can. Adjust the multiplier or precision value accordingly.

2. Using floor and ceil

This method utilizes the floor and ceil functions from '' to round the double to two decimal places.

  • STEP 1: Include the necessary header files.
  • STEP 2: Use 'floor' to round down and 'ceil' to round up.
  • STEP 3: Choose the rounded value based on proximity to the original.
#include 
#include
int main() {
    // Example value to be rounded
    double value = 12.345;
    // Step 1: Round down and round up
    double roundedDown = floor(value * 100) / 100;
    double roundedUp = ceil(value * 100) / 100;
    // Step 2: Choose the rounded value based on proximity
    double roundedValue = (value - roundedDown < roundedUp - value) ? roundedDown : roundedUp;
    // Step 3: Display the result
    std::cout << "Original Value: " << value << std::endl;<br>     std::cout << "Rounded Value: " << roundedValue << std::endl;<br>     return 0;
}

'floor' and 'ceil' are used to round down and round up, respectively.The choice between the rounded down and rounded up values is made based on proximity to the original value.

Output:

3. Using Boost Library

For C++ programming, Boost offers a versatile collection of libraries. The 'numeric_cast' function from the Boost Numeric Conversion library will be used in this example to round a double to two decimal places.

  • STEP 1: Include the necessary header file.
  • STEP 2: Use boost::numeric_cast to round the double.
#include  
#include
int main() {
    // Example value to be rounded
    double value = 12.345;
    // Step 1: Round the double using boost::numeric_cast
    try {
        double roundedValue = boost::numeric_cast(static_cast(value * 100 + 0.5)) / 100.0;
        // Step 2: Display the result
        std::cout << "Original Value: " << value << std::endl;<br>         std::cout << "Rounded Value: " << roundedValue << std::endl;<br>     } catch (const boost::numeric::bad_numeric_cast& e) {
        std::cerr << "Error: " << e.what() << std::endl;<br>     }
    return 0;
}

'boost::numeric_cast' is used to perform the casting with rounding.
The try-catch block is used to catch any exceptions that may occur during the rounding process.
The formula static_cast(value * 100 + 0.5) / 100.0 effectively rounds the double to two decimal places using the numeric_cast mechanism.

Make sure you have Boost installed properly and that your compiler can find the Boost headers. If you still encounter issues, consider checking your Boost installation or consult the Boost documentation for the correct header and library settings.

FAQ Q: In Practical, why we are rounding a number to 2 decimal places? Where it is applied?
A: Numerous real-world applications frequently need rounding values to two decimal places, especially in areas where accuracy and clarity are critical. In the context of financial computations, consider the following real-world example:
  1. Rounding to two decimal places provides a clear and standardized way to represent currency values. It aligns with common currency formatting conventions and makes it easier for users to understand.
  2. Floating-point arithmetic can sometimes introduce small precision errors. Rounding to two decimal places helps mitigate these issues, especially in scenarios where exact precision is not critical.

References

Here are some reference links that can help you with rounding off double values:

More Posts

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

How I Built a React Portfolio in 7 Days That Landed ₹1.2L in Freelance Work

Dharanidharan - Feb 9

How to Write a program to find the sum of the following series 1^1+2^2+3^3... in Python,Java and C

Peter Jones - Nov 23, 2025

How to Generate Random Numbers from 1 to 6 in C++

Danny Jay - Nov 23, 2025

Breaking the AI Data Bottleneck: How Hammerspace's AI Data Platform Eliminates Migration Nightmares

Tom Smithverified - Mar 16
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!