Name

abs

Synopsis

Gives the absolute value of an integer

#include <stdlib.h>
intabs( int n );
long labs( long n );
long long llabs( long long n );

The abs() functions return the absolute value of the integer argument n; if n is greater than or equal to 0, the return value is equal to n. If n is less than 0, the function returns - n.

Example

int amount = -1234;
char currencysym[2] = "$";
char sign[2]        = "-";
div_t dollarsandcents = { 0, 0 };

if ( amount >= 0 )
  sign[0] = '\0';

dollarsandcents = div(abs( amount ), 100 );

printf( "The balance is %s%s%d.%2d\n", sign, currencysym,
        dollarsandcents.quot, dollarsandcents.rem );

This code produces the following output:

The balance is -$12.34

See Also

The C99 absolute value function imaxabs(), declared in the header file inttypes.h for the type intmax_t; the absolute value functions for real numbers, fabs(), fabsf(), and fabsl(); the absolute value functions for complex numbers, cabs(), cabsf(), and cabsl()

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.