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

Absolute values for floats with `fabs`

Absolute values for floats with fabs

What you'll learn: How to calculate the non-negative magnitude of decimal numbers using the math.h library.

In your programming journey, you have likely encountered the abs() function. While that works perfectly for integers, C treats decimal numbers (floats and doubles) differently. If you try to use abs() on a number like -5.5, you might get an unexpected result or a compiler warning because abs() expects a whole number.

To handle floating-point numbers, we use a specific function called fabs(). The "f" stands for "float," and it is your go-to tool for finding the distance between a number and zero.

The "Distance" Concept

Think of fabs() like a car's odometer. It doesn't matter if you drive five miles forward (positive) or five miles in reverse (negative); the odometer still shows that you traveled five miles. You are interested in the magnitude of the movement, not the direction.

In programming, we often need this when calculating the difference between two values where the order doesn't matter. For example, if you are checking if a player is "close enough" to a target, you want to know the distance, not whether they are to the left or right of it.

Implementing fabs

To use fabs(), you must include the <math.h> header at the top of your file. This tells the compiler where to find the math instructions.

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

int main() {
    double accountBalance = -150.75;
    double debtAmount;

    // fabs converts -150.75 to 150.75
    debtAmount = fabs(accountBalance);

    printf("Your balance is: %.2f\n", accountBalance);
    printf("The absolute debt magnitude is: %.2f\n", debtAmount);

    return 0;
}

Why two different functions?

C is a "statically typed" language that prioritizes performance. By having a dedicated function for floating-point numbers (fabs) and another for integers (abs), the computer can process the math using the most efficient instructions for that specific data type.

If you pass a negative double to fabs(), it simply strips away the negative sign and returns the positive version. If you pass a positive double, it returns it exactly as it is.

Key takeaway

Use fabs() from the math.h library to get the positive magnitude of a floating-point number.