abs()

Description

Calculates the absolute value of a number.

Syntax

abs(x)

Parameter Values

  • x: the number

Return Values

  • x: if x is greater than or equal to 0.
  • -x: if x is less than 0.

Example Code

void setup() { Serial.begin(9600); int x = -4; int y = abs(x); Serial.print("The absolute value of of "); Serial.print(x); Serial.print(" is "); Serial.println(y); } void loop() {}

The result in Serial Monitor:

Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
The absolute value of of -4 is 4
Ln 11, Col 1
Arduino Uno on COM15
2

※ NOTES AND WARNINGS:

Because of the way the abs() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results.

abs(a++); // avoid this - yields incorrect results // use this instead: abs(a); a++; // keep other math outside the function

See Also

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables .

※ OUR MESSAGES