Wednesday 22 September 2021

Python: rounding off to n decimal places

Using string format method, we can round of a number.

 

Example

str1 = '{0:.2f}'.format(10.23456)

 

Find the below working application.

 

round_to_decimal_places.py

str1 = '{0:.2f}'.format(10.23456)
str2 = '{0:.3f}'.format(10.23456)
str3 = '{0:.4f}'.format(10.23456)

print('Rounding to 2 decimal places ', str1)
print('Rounding to 3 decimal places ', str2)
print('Rounding to 4 decimal places ', str3)

Output

Rounding to 2 decimal places  10.23
Rounding to 3 decimal places  10.235
Rounding to 4 decimal places  10.2346


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment