How to Round Floating-Point Number to 2 Decimals in C++
-
Using the Standard Library’s
std::round
-
Using
std::setprecision
for Output Formatting -
Use the
printf
Function Format Specifiers to Round Floating-Point Number to 2 Decimals in C++ -
Use
fprintf
Function Format Specifiers to Round Floating-Point Number to 2 Decimals in C++ - Creating a Custom Rounding Function
- Conclusion
- FAQ

When working with floating-point numbers in C++, precision is often crucial, especially in financial applications or scientific calculations. Rounding to two decimal places can help present data in a more user-friendly manner.
In this article, we will explore various methods to round floating-point numbers to two decimals in C++. Whether you’re a beginner or an experienced programmer, you’ll find these approaches easy to follow. We’ll cover using standard library functions, custom functions, and formatting outputs for display. Let’s dive into the world of rounding in C++ and make your numbers look just right!
Using the Standard Library’s std::round
The C++ Standard Library provides a convenient function, std::round
, which can be utilized to round numbers. To round a floating-point number to two decimal places, we can multiply the number by 100, round it, and then divide by 100. This method is straightforward and efficient.
Here is how you can implement it:
#include <iostream>
#include <cmath>
double roundToTwoDecimals(double value) {
return std::round(value * 100) / 100;
}
int main() {
double number = 3.14159;
double roundedNumber = roundToTwoDecimals(number);
std::cout << "Rounded Number: " << roundedNumber << std::endl;
return 0;
}
Output:
Rounded Number: 3.14
In this example, we define a function roundToTwoDecimals
that takes a double as an argument. Inside the function, we multiply the value by 100, apply std::round
, and then divide by 100 to get the rounded result. In the main
function, we call this rounding function with a floating-point number, and the result is printed to the console. This method is efficient and leverages the capabilities of the C++ Standard Library.
Using std::setprecision
for Output Formatting
Another effective way to round floating-point numbers in C++ is by using the std::setprecision
manipulator from the <iomanip>
library. This method is particularly useful when you want to control the number of decimal places displayed in your output without altering the actual value of the variable.
Here’s how you can do it:
#include <iostream>
#include <iomanip>
int main() {
double number = 3.14159;
std::cout << std::fixed << std::setprecision(2) << "Rounded Number: " << number << std::endl;
return 0;
}
Output:
Rounded Number: 3.14
In this code snippet, we include the <iomanip>
library to access the std::setprecision
function. By using std::fixed
, we ensure that the output is in fixed-point notation, and std::setprecision(2)
sets the precision to two decimal places. This method allows you to display the number as rounded without changing its underlying value. It’s particularly useful when you want to maintain the original precision for further calculations while presenting a cleaner output.
Use the printf
Function Format Specifiers to Round Floating-Point Number to 2 Decimals in C++
Floating-point numbers have special binary representation, which entails that real numbers can’t be represented exactly by the machines. Thus, it’s common to resort to rounding functions when operating on the floating-point numbers and doing calculations on them. In this case, though, we only need to output a certain portion of the numbers’ fractional part.
The first solution is to utilize the printf
function to output formatted text to the stdout
stream. Note that the regular format specifier for the float
numbers - %f
should be modified to %.2f
. The latter notation ensures that only 2 decimals are printed from the number, and at the same time, it does the rounding according to the common mathematical rules. Mind that, a similar notation can be used with format specifiers of other data types.
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main() {
vector<double> floats{-3.512312, -21.1123, -1.99, 0.129, 2.5, 3.111};
for (auto &item : floats) {
printf("%.2f; ", item);
}
return EXIT_SUCCESS;
}
Output:
-3.51; -21.11; -1.99; 0.13; 2.50; 3.11;
Use fprintf
Function Format Specifiers to Round Floating-Point Number to 2 Decimals in C++
fprintf
is another function that can be used to do the output formatting like the printf
call and additionally, it can write to any FILE*
stream object that can be passed as the first argument. In the following example, we demonstrate printing to the stderr
stream, an unbuffered version of stdout
for error reporting and logging.
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main() {
vector<double> floats{-3.512312, -21.1123, -1.99, 0.129, 2.5, 3.111};
for (auto &item : floats) {
fprintf(stderr, "%.2f; ", item);
}
return EXIT_SUCCESS;
}
Output:
-3.51; -21.11; -1.99; 0.13; 2.50; 3.11;
The above code demonstrates the use of fprintf
to output formatted data to the standard error stream (stderr
). It creates a vector of double-precision floating-point numbers and then uses a range-based for loop to iterate over each element. The fprintf
function is used to print each number to stderr
with two decimal places of precision, followed by a semicolon and space.
Using fprintf
with stderr
is particularly useful for error reporting or logging, as stderr
is typically unbuffered, meaning output appears immediately. This can be crucial for debugging or when immediate output is necessary. The “%.2f” format specifier ensures that each number is printed with exactly two decimal places, providing consistent formatting for the output.
Creating a Custom Rounding Function
If you prefer a more hands-on approach, you can create your own rounding function. This method gives you the flexibility to define how rounding should be handled, allowing for more complex rounding logic if necessary.
Here’s an example of a custom rounding function:
#include <iostream>
double customRound(double value, int decimals) {
double factor = pow(10, decimals);
return std::round(value * factor) / factor;
}
int main() {
double number = 3.14159;
double roundedNumber = customRound(number, 2);
std::cout << "Rounded Number: " << roundedNumber << std::endl;
return 0;
}
Output:
Rounded Number: 3.14
In this example, we define a function called customRound
that takes a double value and the number of decimal places as parameters. We calculate a factor based on the number of decimals, multiply the original value by this factor, round it, and then divide by the factor to get the rounded result. This approach is very flexible and can be adapted for any number of decimal places, making it a versatile solution for rounding needs.
Conclusion
In summary, rounding floating-point numbers to two decimal places in C++ can be achieved through various methods, including using the Standard Library’s std::round
, output formatting with std::setprecision
, and creating a custom rounding function. Each method has its advantages, depending on your specific needs. Whether you’re displaying financial data or scientific measurements, these techniques will help ensure that your numbers are both accurate and aesthetically pleasing. By mastering these methods, you can enhance your C++ programming skills and improve the quality of your numerical outputs.
FAQ
-
What is the purpose of rounding floating-point numbers?
Rounding helps present numbers in a more readable format, especially in applications like finance, where precision is crucial. -
Can I round to more than two decimal places using the methods described?
Yes, you can easily modify the methods to round to any number of decimal places by changing the multiplier and divisor. -
Is there a performance difference between these rounding methods?
Generally, the performance difference is negligible for most applications, but usingstd::round
is typically faster for simple rounding tasks. -
Can I round negative numbers using these methods?
Yes, all the methods described will work correctly with negative floating-point numbers. -
Are there any libraries in C++ specifically for numerical computations?
Yes, libraries like Boost or Eigen provide extensive functionalities for numerical computations, including rounding and precision management.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook