How to get the Absolute Value of a Number in Python
To get the absolute value of a number in Python, use the
abs() method. This method will convert integers and floating-point numbers to their absolute equivalents and for complex numbers their magnitude.
Get the Absolute Value of a Number
To get the absolute value of a floating-point or integer pass it inside the
() (parenthesis) of the
abs() method. Let's try out a couple of examples and print the results.
decimal = -1.354 integer = -34564 dec_abs = abs(decimal) int_abs = abs(integer) print(dec_abs) print(int_abs)
Get the Absolute Value of a Complex Number
A complex number consists of a real number and an imaginary unit to represent a number that can't be represented numerically. If we pass a complex number into
abs() we will get its magnitude.
comp = 10 + 10j comp_abs = abs(comp) print(comp_abs)
You now know how to get the absolute value of any given number using
abs() in Python