Library contents

C++ std::nearbyint

Round to the nearest whole unit using the even neighbour at an exact halfway point.

A simple example

std::nearbyint

  1. Start with 2.5
  2. Do this Round a tie to an even integer
  3. Result 2
The two nearest integers are 2 and 3. The even one is 2 under ties-to-even rounding. This example assumes the default rounding mode.
lesson.cpp
#include <iostream>
#include <cmath>

int main() {
    std::cout << (std::nearbyint(2.5)) << '\n';
}
Output
2

Syntax

C++ syntax
std::nearbyint(kilograms)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Round a scale reading at an exact tie

A parcel scale sits exactly halfway between two display values. The warehouse needs a consistent tie rule so repeated weighings follow the same rounding convention.

From the programconst double kilograms = 4.5
Result4.000
lesson.cpp
#include <cmath>
#include <cstdio>

int main() {
    const double kilograms = 4.5;

    std::printf("%.3f\n", std::nearbyint(kilograms));
    return 0;
}
Output
4.000

A reading of 4.5 is halfway between 4 and 5. The even neighbour is 4.

Advertisements

Apply ties-to-even to a parcel scale

A parcel scale reports a value exactly between neighboring whole units. Compare how a tie is resolved on the display when the nearest even value lies on a different side of the measurement.

From the programconst double weight = 5.5
Result6.000
lesson.cpp
#include <cmath>
#include <cstdio>

int main() {
    const double weight = 5.5;

    std::printf("%.3f\n", std::nearbyint(weight));
    return 0;
}
Output
6.000

At an exact tie between five and six the even neighbour is six.

Round a parcel reading for a whole-unit display

A mailroom display shows only whole grams while its scale records tenths. A parcel weighs 18.7 grams and the display rounds to the nearest gram.

Given18.7 g → nearest whole gram
Worked result19 g

The reading lies closer to nineteen than eighteen.

What to watch for

This operation follows the active floating-point rounding mode. The example uses the default nearest-even mode.

Documentation for std::nearbyint