How to round to two decimals in Python?

ItsMyCode |

This tutorial will learn how to round to two decimals in Python using round() and format() methods.

Round to two decimals in Python

When you deal with mathematical calculations in Numpy or Python, you will often get a lot of decimal values during the calculation. There are 2 ways to round off the decimals in Python. Let us take a look at both approaches in detail.

Using round() Method

The round() method returns the floating-point number, the rounded version of a specified number with the specified number of decimals.

Syntax – round(number, ndigits)

  • number – the number to be rounded, can be an integer, decimal/floating.
  • ndigits (optional) – number of decimals to use when rounding the number. The default value is 0.

Example – Round to two decimal places

# integer round off
print("Integer round off Mid value ",round(7))

# Python code to round off floating number using default value
print("Floating round off ",round(7.7))

# Python code to round off floating number with mid value
print("Floating round off Mid value ",round(7.5))

# floating number round to two decimal places
distance= 4.3847594892369461
print ("The total distance is ", round(distance,2))

Output

Integer round off Mid value 7
Floating round off 8
Floating round off Mid value 8
The total distance is 4.38

*Note: * The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

Using format() method

You can use the format()method to handle the precision of the floating-point numbers, and there are many ways to set the precision of the number in Python.

Syntax – string.format(value)

  • : introduces the format spec
  • 0 enables sign-aware zero-padding for numeric types
  • .2 sets the precision to 2
  • f displays the number as a fixed-point number

Alternatively, *Using “%”:- *%” operator is used to format as well as set precision in Python.

# Python code to round to two decimals using format

# initializing value
distance= 4.7287543

# using format() to print value with 2 decimal places
print ("The value of number till 2 decimal place(using format()) is : ",end="")
print ("{0:.2f}".format(distance))

# using "%" to print value with 2 decimal places
print ("The value of number till 2 decimal place(using %) is : ",end="")
print ('%.2f'%distance)

Output

The value of number with 2 decimal place(using format()) is : 4.73
The value of number with 2 decimal place(using %) is : 4.73

15