Course contentsShow
← C
Lesson 865 of 1,21912. The Standard LibraryFree lesson

Truncation and remainder: `trunc` and `fmod`

Truncation and remainder: trunc and fmod

What you'll learn: How to strip decimals away from a number and calculate remainders for floating-point math using the <math.h> library.

When working with decimals (double), the standard % operator you use for integers won't work. To handle remainders and rounding for floating-point numbers, we turn to two specific functions: trunc and fmod.

Truncation: The "Chop"

The trunc() function is the simplest way to turn a decimal into a whole number. Think of it like a physical guillotine for digits. It doesn't care about rounding up or down; it simply "chops off" everything after the decimal point.

If you have 3.99, trunc gives you 3.0. If you have -3.99, it gives you -3.0. It always moves the number toward zero. This is useful when you only care about the "whole" part of a measurement and want to discard the fractional noise.

Fmod: The Floating Remainder

In integer math, 7 % 3 is 1 because 3 goes into 7 twice with 1 left over. However, the % operator results in an error if you try to use it on a double. To find the remainder of a decimal division, we use fmod(x, y).

Imagine you are tiling a floor that is 10.5 feet wide using tiles that are 4.0 feet wide. You can fit two full tiles, but how much space is left? Calling fmod(10.5, 4.0) will return 2.5. It calculates how many full units of y fit into x and hands you the leftover piece.

Seeing it in code

To use these, you must include <math.h> at the top of your file.

#include <stdio.h>
#include <math.h>

int main() {
    double distance = 14.85;
    double lap_length = 4.2;

    // Truncate the distance
    double whole_part = trunc(distance); 
    printf("Truncated: %.2f\n", whole_part); // Outputs 14.00

    // Find the remainder of the laps
    double leftover = fmod(distance, lap_length);
    printf("Remaining distance: %.2f\n", leftover); // Outputs 2.25

    return 0;
}

Key takeaway

Use trunc to discard decimals without rounding, and use fmod as the floating-point version of the modulo (%) operator.