C fabs() Function

Definition
In C, fabs() returns the absolute value of a double. It drops a minus sign and keeps the size. fabs(-3.5) is 3.5.
You pass one double. The result is a double that is never negative. Include <math.h>. For an int, use abs().
Syntax
Pass the floating-point number. Start with this call.
| Call | What it does |
|---|
fabs(-3.5) | Drops the minus sign and returns 3.5. |
Include <math.h>. On GCC, link with -lm. Do not use abs() for a double.
Library declarations
double fabs(double x);
float fabsf(float x);
long double fabsl(long double x);
Parameters
| Parameter | Description |
|---|
| x | Required. The double whose sign you want to drop. |
Return Value
| Return Value | Description |
|---|
| Non-negative double | The same magnitude, with the minus sign removed. |
C Examples
Example 1 — Basic Absolute Value
Flip negatives; leave positives unchanged.
#include <stdio.h>
#include <math.h>
int main(void) {
printf("%.2f\n", fabs(-12.34));
printf("%.2f\n", fabs(3.5));
return 0;
}
How It Works
- Include math.h. That declares
fabs. - Negative input.
-12.34 becomes 12.34. - Positive input.
3.5 stays 3.5. - Result type. Return value is still
double.
Example 2 — Distance on a Line
Absolute difference gives a distance that does not depend on order.
#include <stdio.h>
#include <math.h>
int main(void) {
double a = 3.0;
double b = 10.0;
double d = fabs(a - b);
printf("distance = %.1f\n", d);
return 0;
}
How It Works
- Subtract.
a - b is -7.0. - Take fabs. Magnitude becomes
7.0. - Order does not matter.
fabs(b - a) is the same distance. - Useful pattern. Gaps, deltas, and errors often need this.
Example 3 — Tolerance / Near-Equal Check
Floating-point values rarely match exactly. Compare with a small allowed error.
#include <stdio.h>
#include <math.h>
int main(void) {
double x = 0.1 + 0.2;
double eps = 1e-9;
if (fabs(x - 0.3) < eps) {
printf("close enough\n");
} else {
printf("not close\n");
}
return 0;
}
How It Works
- 0.1 + 0.2 is messy. Binary floats may not equal
0.3 exactly. - Measure the gap.
fabs(x - 0.3) is a tiny error. - Compare to eps. If the gap is smaller than
1e-9, treat them as equal. - Safer than ==. Exact equality checks on floats are often unreliable.
Frequently Asked Questions
fabs() returns the absolute value of a double. fabs(-3.5) is 3.5.
x is required. It is the double whose sign you want to drop.
A non-negative double with the same magnitude.
Include <math.h>. On GCC, link with -lm.
abs() takes an int and is declared in stdlib.h. fabs() takes a double and is declared in math.h.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful