Library contents

C round

Round an estimate to the nearest whole minute before showing it to a customer.

A simple example

round

  1. Start with 2.6
  2. Do this Round to the nearest integer
  3. Result 3
The distance to 3 is 0.4. The distance to 2 is 0.6.
lesson.c
#include <stdio.h>
#include <math.h>

int main(void) {
    printf("%.15g\n", (double) (round(2.6)));
}
Output
3

Syntax

C syntax
round(minutes)
Run these examples in C

Save one example at a time as lesson.c. Use C17 and a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Display a delivery estimate in minutes

A courier predicts a delivery time with a fractional minute. Round the estimate for a whole-minute display and examine what happens when the prediction falls exactly between two displayed minutes.

From the programdouble minutes = 12.6
Result13.000
lesson.c
#include <math.h>
#include <stdio.h>

int main(void) {
    double minutes = 12.6;

    printf("%.3f\n", round(minutes));
    return 0;
}
Output
13.000

Twelve minutes and six tenths is nearer thirteen than twelve.

Advertisements

Show a bus arrival on a station board

A transit or delivery display has room only for whole minutes. Convert a fractional estimate for display while keeping the more precise original estimate available to the scheduler.

From the programdouble minutes = 7.8
Result8.000
lesson.c
#include <math.h>
#include <stdio.h>

int main(void) {
    double minutes = 7.8;

    printf("%.3f\n", round(minutes));
    return 0;
}
Output
8.000

A 7.8-minute prediction displays as eight minutes. Keep the full estimate for scheduling calculations.

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

round rounds exact half values away from zero, so -2.5 becomes -3.

Documentation for round