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)

  • digits is 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 ≤ number

  • ceil() → smallest integer ≥ number


4. Using NumPy for Arrays


 

  • np.round() → rounds to specified decimals

  • np.floor() → element-wise floor

  • np.ceil() → element-wise ceiling


✅ 5. Using decimal Module for Precision Control


 

  • Provides precise decimal rounding

  • Useful in financial calculations


🎯 Practice Exercises

  1. Round 5.6789 to 0, 1, 2, 3 decimal places.

  2. Create a NumPy array [2.345, 6.789, 1.234] and round it to 2 decimals.

  3. Use the decimal module to round 7.555 to 2 decimal places using ROUND_HALF_UP.

You may also like...