In C++, std::fabs() returns the absolute value of a decimal number. The name means "floating-point absolute value". It makes any negative double positive and leaves a positive one alone.
It is the same idea as std::abs(), but its name makes it clear that you are working with decimals. It was in C before C++ got the overloaded abs(), so you will see it in a lot of older code.
std::fabs() is declared in <cmath> and is part of the group Absolute value and sign. These functions work with the sign of a number. abs() and fabs() remove a minus sign, and copysign() and signbit() copy or read it.
Syntax
Include <cmath> and call std::fabs. Start with these lines.
C++
double a = std::fabs(-4.5); // double version
float b = std::fabs(-4.5f); // float version
Call
What it does
std::fabs(-4.5)
Passes a double and returns a double. Here the result is 4.5.
std::fabs(-4.5f)
Passes a float, so the float overload runs and returns a float.
std::fabs(-4)
An integer is converted to double. Returns 4 as a double.
Write std::fabs so the C++ overloads for float, double, and long double are used.
Library declarations
C++
float fabs(float x);
double fabs(double x);
long double fabs(long double x);
double fabs(Integer x); // for integer types
Parameters
Parameter
Description
x
Required. A float, double, or long double. An integer is converted to double.
Return Value
Return Value
Description
Absolute value
The magnitude of x with a positive sign.
+0.0
Returned for both 0.0 and -0.0.
inf / NaN
fabs(-inf) is inf. fabs(NaN) is NaN.
C++ Examples
Example 1 — Absolute Value of Several Decimals
Loop over a few numbers, including negative zero, and print the original next to its fabs() result.
C++
#include <cmath>
#include <iostream>
int main() {
double values[] = {-3.5, 0.0, 2.25, -0.0};
for (double v : values) {
std::cout << "fabs(" << v << ") = " << std::fabs(v) << '\n';
}
return 0;
}
std::numeric_limits<double>::infinity() is a real value, and fabs(-inf) turns minus infinity into plain inf.
std::nan("") creates a NaN. fabs() keeps it as NaN, so std::isnan() prints 1.
-1e308 * 10 overflows to -inf before fabs() is called, so the final answer is inf.
Frequently Asked Questions
std::fabs() returns the absolute value of a floating-point number. It removes the minus sign and keeps the size, so -4.5 becomes 4.5.
The absolute value as float, double, or long double. For -0.0 the result is +0.0, for -inf it is inf, and for NaN it is NaN.
For decimals, yes. std::fabs(x) and std::abs(x) give the same result for a double. fabs() only works with floating-point values, while abs() also has integer versions.
No. It returns a new value. Write x = std::fabs(x); if you want to replace the variable.
Include <cmath> and write std::fabs(). That always works and picks the C++ overloads. The global name ::fabs often works too, but the standard does not promise it, and it may only take a double.