I’m working on a c++ round down where I need to round down floating-point numbers to the nearest integer. I know about standard rounding functions, but I specifically need to ensure that numbers always round downward (i.e., towards negative infinity).
For example:
4.7 should become 4
-2.3 should become -3
After some research, I found that C++ provides several ways to achieve this, and I’d love to hear your thoughts on the best approach.
- Using floor() from <cmath>
One of the simplest ways is using the floor() function from the <cmath> library.
cpp
Copy
Edit
#include <iostream>
#include <cmath>
int main() {
double num1 = 4.7;
double num2 = -2.3;
std::cout << "Floor of " << num1 << " is " << std::floor(num1) << std::endl;
std::cout << "Floor of " << num2 << " is " << std::floor(num2) << std::endl;
return 0;
}
Output:
csharp
Copy
Edit
Floor of 4.7 is 4
Floor of -2.3 is -3
This function is efficient and works perfectly for my case.
- Using Type Casting (Only for Positive Numbers)
Another approach (which only works for positive values) is using an implicit conversion to int.
cpp
Copy
Edit
#include <iostream>
int main() {
double num = 4.7;
std::cout << "Implicit cast: " << (int)num << std::endl;
return 0;
}
However, this truncates towards zero rather than always rounding down, so it won’t work correctly for negative numbers.
- Using Integer Division (For Specific Cases)
In some cases, if you're dealing with division and want to round down, you can use integer division.
cpp
Copy
Edit
int roundDown(int a, int b) {
return a / b; // Integer division naturally discards decimal places
}
Again, this method is useful in some situations but doesn’t apply to general floating-point rounding.
- Using std::floor() in Modern C++ with std::vector (Example for Multiple Values)
If you have a list of numbers, you can apply std::floor() to all of them using a loop or a lambda function with std::transform.
cpp
Copy
Edit
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
int main() {
std::vector<double> numbers = {3.9, 5.2, -1.7, -4.3};
std::vector<int> flooredNumbers;
std::transform(numbers.begin(), numbers.end(), std::back_inserter(flooredNumbers),
[](double num) { return std::floor(num); });
for (int n : flooredNumbers) {
std::cout << n << " ";
}
return 0;
}
Conclusion
From what I’ve tested, std::floor() is the best and most reliable method to always round numbers downward. Type casting and integer division can work in some cases, but they don’t guarantee correct behavior for negative numbers.