0
0
Pythonprogramming~5 mins

abs() and round() in Python

Choose your learning style9 modes available
Introduction

The abs() function helps you find how far a number is from zero, ignoring if it's negative or positive. The round() function helps you make numbers simpler by cutting them to fewer decimal places.

When you want to know the size of a number without caring about its sign, like measuring distance.
When you need to clean up a number to fewer decimals for easier reading or reporting.
When comparing numbers and you want to ignore small differences caused by negative signs.
When working with money and you want to round prices to two decimal places.
When you want to avoid very long decimal numbers in your results.
Syntax
Python
abs(number)
round(number, ndigits=0)

abs() takes one number and returns its positive value.

round() takes a number and an optional number of decimal places (default is 0) to round to.

Examples
Returns 5 and 3 because abs() removes the negative sign.
Python
abs(-5)
abs(3)
Rounds 3.14159 to 3 (no decimals) and 3.14 (two decimals).
Python
round(3.14159)
round(3.14159, 2)
Rounds to 2.718 and -2.7 respectively, showing it works with negative numbers too.
Python
round(2.71828, 3)
round(-2.71828, 1)
Sample Program

This program shows how abs() removes the negative sign and how round() cuts decimals to make numbers simpler.

Python
number1 = -7.89
number2 = 4.5678

print(f"Absolute of {number1} is", abs(number1))
print(f"Rounded {number2} to 2 decimals is", round(number2, 2))
print(f"Rounded {number2} with no decimals is", round(number2))
OutputSuccess
Important Notes

abs() works with integers, floats, and even complex numbers (returns magnitude).

round() returns an integer if no decimals are given, otherwise a float.

Rounding follows the usual rules: 0.5 and above rounds up, below 0.5 rounds down.

Summary

abs() gives the positive distance of a number from zero.

round() simplifies numbers by cutting decimals to a chosen length.

Both help make numbers easier to understand and use in everyday tasks.