Rounding Decimals
🔢 Rounding Decimals in Python
Python provides several ways to round numbers to a specific number of decimal places. You can use built-in functions, string formatting, or NumPy for arrays.
1. Using round() Function
Syntax:
round(number, digits)digitsis optional; default is 0
2. Using String Formatting
.2f→ 2 decimal places.3f→ 3 decimal places
3. Using math.floor() and math.ceil()
floor()→ largest integer ≤ numberceil()→ smallest integer ≥ number
4. Using NumPy for Arrays
np.round()→ rounds to specified decimalsnp.floor()→ element-wise floornp.ceil()→ element-wise ceiling
✅ 5. Using decimal Module for Precision Control
Provides precise decimal rounding
Useful in financial calculations
🎯 Practice Exercises
Round
5.6789to 0, 1, 2, 3 decimal places.Create a NumPy array
[2.345, 6.789, 1.234]and round it to 2 decimals.Use the
decimalmodule to round7.555to 2 decimal places usingROUND_HALF_UP.
