In C++, std::lround(x) rounds a decimal to the nearest whole number and gives it to you as a long. It is std::round() with an integer result, so no cast is needed.
A number exactly halfway goes away from zero: lround(2.5) is 3 and lround(-2.5) is -3. The current rounding mode is ignored. If the number is too large for a long, the result is not defined.
std::lround() is declared in <cmath> and is part of the group Rounding. Rounding functions turn a fractional number into a whole number. They differ in which way they go for negative numbers and for ties such as 2.5.
Syntax
Include <cmath> and call std::lround. Start with these lines.
C++
long a = std::lround(2.5); // 3
long b = std::lround(-2.5); // -3
long c = std::lround(2.4); // 2
Call
What it does
std::lround(2.5)
Exactly halfway, so it goes away from zero. Returns 3.
std::lround(-2.5)
Away from zero for a negative number means -3.
std::lround(2.4f)
The float overload also returns a long. The result is 2.
The return type is always long. Use llround() for long long.
Library declarations
C++
long lround(float x);
long lround(double x);
long lround(long double x);
long lround(Integer x); // for integer types
Parameters
Parameter
Description
x
Required. The number to round. It can be float, double, long double, or an integer type (converted to double).
Return Value
Return Value
Description
long
The nearest whole number. Halves are rounded away from zero.
Unspecified
If the result is out of range for a long, or x is NaN or infinity.
C++ Examples
Example 1 — Round Several Numbers to a long
The results are whole numbers of type long. Halves go away from zero.
C++
#include <cmath>
#include <iostream>
int main() {
double values[] = {2.5, -2.5, 2.4, 2.6, -0.4};
for (double v : values) {
long r = std::lround(v);
std::cout << "lround(" << v << ") = " << r << '\n';
}
return 0;
}
Average 86.25 -> grade 86
Average 70.5 -> grade 71
How It Works
The divisions use 4.0 and 2.0, so the averages keep their decimals: 86.25 and 70.5.
86.25 is closer to 86, so lround() returns 86.
70.5 is exactly halfway and goes away from zero, up to 71. A student with a half point average gets the higher grade.
Frequently Asked Questions
std::lround(x) rounds x to the nearest whole number and returns it as a long. A half goes away from zero, so lround(2.5) is 3 and lround(-2.5) is -3.
The nearest whole number as a long, with halves rounded away from zero. If the result does not fit in a long, the value is unspecified.
They round the same way, halves away from zero. round() returns a double like 3.0, and lround() returns a long like 3, so you do not need a cast.
The result is unspecified and an invalid exception is raised. Check the range first, or use llround() for bigger numbers.
Include <cmath> and write std::lround(). That always works and picks the C++ overloads. The global name ::lround often works too, but the standard does not promise it, and it may only take a double.