Python – Round float number to specific decimal places

Python – Round a Number to Specific Decimal Places

To round a given number to specific decimal places, call round() function and pass the given number and the number of decimal places, as arguments.

Syntax

The syntax of round() function is

round(number, ndigits)

where

numberThe number whose decimal places has to be rounded.
ndigits[Optional] Number of decimal places after the decimal point to be preserved in the output. Default value is 0.

Examples

1. Round Number to 2 Decimal Places in Python

In this example, we take a float value with five digits after decimal point, and round it to two decimal places.

Python Program

number = 3.14159
ndigits = 2
result = round(number, ndigits)
print('Original Value :', number)
print('Rounded Value  :', result)
Run Code Copy

Output

Original Value : 3.14159
Rounded Value  : 3.14

2. Round Number to a Single Decimal Place in Python

In this example, we take a float value with five digits after decimal point, and round it to single decimal place.

Python Program

number = 3.14159
ndigits = 1
result = round(number, ndigits)
print('Original Value :', number)
print('Rounded Value  :', result)
Run Code Copy

Output

Original Value : 3.14159
Rounded Value  : 3.1

Summary

In this tutorial of Python Examples, we learned how to round a given number to specified number of decimal places.

Related Tutorials

Code copied to clipboard successfully 👍