Explain Codes LogoExplain Codes Logo

How to round to 2 decimals with Python?

python
functions
best-practices
dataframe
Anton ShumikhinbyAnton Shumikhin·Sep 3, 2024
TLDR

round(): Python's go-to function for rounding to 2 decimal places: round(3.14159, 2) -> 3.14.

print(round(3.14159, 2)) # 3.14, π to the rescue!

More quickfire solutions

String formatting for outputs

Format as string for display purposes:

formatted_number = "{:.2f}".format(3.14159) print(formatted_number) # '3.14'

F-strings for compact code

Python 3.6 onwards, use f-string formatting for cleaner code:

number = 3.14159 print(f"{number:.2f}") # '3.14'

Rounding in the wild

For calculations, apply round() where every decimal counts!

Deep insights into accurate rounding

Breakdown of round()

Two-input function round(): the number and the decimal places. For 0.5 situations, it even-steven rounds to the nearest even number (bankers' rounding).

Weird corners of precision and ties

Understand how Python plays with ties and precision. With obedience to the IEEE 754 standard, unpredictable outcomes spawn from binary representation of decimals:

print(round(2.675, 2)) # Expect 2.68 but you get 2.67. Yes, we're serious

Special functions from Python's math module

Different flavours of rounding with Python’s native math module:

  • math.ceil(): upwards round off
import math print(math.ceil(2.1)) # returns 3 as it has a thing for the ceiling
  • math.floor(): downward round off
print(math.floor(2.9)) # goes down to 2, gravity bound!

Tailor-made rounding function

A custom function for niche rounding needs with up and down options to specified decimal places:

def custom_round(number, decimals=2, direction='nearest'): multiplier = 10 ** decimals if direction == 'up': return math.ceil(number * multiplier) / multiplier elif direction == 'down': return math.floor(number * multiplier) / multiplier return round(number, decimals)

Formatting numbers and managing precision

Reining format with zeroes and signs

Maintain format harmony with str.format(). The coveted '0' flag enforces zero-padding for a uniform numeric display:

print("{:06.2f}".format(3.14)) # Here's '003.14', zero regret!

Rounding for display vs computation

Context matters! For display, apply string methods. For calculations, use round(). String methods respect the underlying value with a smart makeup only policy:

# For display: print(f"{3.14159:.2f}") # '3.14' # For calculation: result = round(3.14159, 2) # 3.14 because Python cares

Python FAQ for adaptive learnings

Test your knowledge with a quick self-quiz:

  • Kouhai: How will "{:03.2f}".format(3.14) display? Sensei: '03.14'
  • Kouhai: Round off 2.357 to 2.36 using round()? Sensei: round(2.357, 2)
  • Kouhai: Does formatting a number put its equation value at stake? Sensei: No, Python leaves the inner number at peace, ensures beautiful display only.