TL;DR – The built-in Python round function allows you to round numbers.
How to round in Python
round function rounds a floating point number to a specified amount of decimals:
number = round(37.8452950483520, 4) print(number) number2 = round(37.8452950483520, 2) print(number2) number3 = round(37.8452950483520) print(number3)
You can also use Python
round for negative numbers:
number = round(-14.573883749392, 4) print(number) number2 = round(-14.573883749392, 2) print(number2) number3 = round(-14.573883749392) print(number3)
Theory is great, but we recommend digging deeper!
The syntax for round in Python
round function takes up to two arguments:
- A floating point number to round
- A number of decimals to round the number to
The second argument is optional: if you skip it, the number will be rounded to the nearest integer (no decimals). If using both, you have to separate the arguments with a comma:
Python round: useful tips
- Make sure you define both arguments for rounding in Python in numbers – otherwise, a TypeError will fire.
- In some cases, you might get inconsistent results for example,
2.75is rounded to
2.65is rounded to
2.6. It's not a bug: the system simply cannot represent some decimal fractions exactly as floats.