How to display a float with two decimal places in Python?

Numbers with a decimal point are considered floating numbers, also referred to as real numbers. A floating number has six decimal points by default, but we can adjust this using the methods described below.

In this article, we are going to find out how to display a float with two decimal places in Python.

The first technique is to employ the format method. The format will be included in a print statement, and it will be referenced using curly braces, with the number of decimal points mentioned inside the curly braces.

Example

In the example given below, we are taking a floating number as input and we are displaying it with 2 decimal points.

num = 12.263241

print("Given floating number is")
print(num)

print("The floating number rounded up to 2 decimal points is")
print("{:12.2f}".format(num))


Output

The output of the above example is as shown below−

Given floating number is
12.263241
The floating number rounded up to 2 decimal points is
12.26


Using % operator

The second method is to employ the percent operator. It's identical to the format technique, except instead of format, we'll use percent, and instead of curly braces, we'll use percent.

Example

In the example given below, we are taking a floating number as input and we are displaying it with 2 decimal points using % operator −

num = 12.26549

print("Given floating number is")
print(num)

print("The floating number rounded up to 2 decimal points is")
print("% .2f" %num)


Output

The output of the above example is given below −

Given floating number is
12.26549
The floating number rounded up to 2 decimal points is
12.27


Using round() operator

The round operator is used in the third approach. The round operator will take the number and the amount of decimal points as input and return the revised value as output.

Example

In the example given below, we are taking a floating number as input and we are displaying it in only 2 decimal points using round() operator. −

num = 12.26549

print("Given floating number is")
print(num)

print("The floating number rounded up to 2 decimal points is")
print(round(num,2))


Output

The output of the above example is given below −

Given floating number is
12.26549
The floating number rounded up to 2 decimal points is
12.27