How to Format Number to 2 Decimal Places in Python?

12-Jun-2023

.

Admin

How to Format Number to 2 Decimal Places in Python?

Hi Dev,

This article will provide an example of how to format numbers to 2 decimal places in Python. We will use python to convert numbers to float with 2 decimal places. I’m going to show you python numbers to 2 decimal places. I explained simply step-by-step Python format numbers to 2 decimal places. So, let's follow a few steps to create an example of a Python round number to 2 decimal places.

You can convert a number to a float with 2 decimal places in Python by using the round() function. Here is an example:

Example 1:


In this example, we start with the number 4.14159265359. We then use the round() function to round the number to 2 decimal places, and assign the result to the float_number variable. Finally, we print the float_number variable, which will output 4.14.

main.py

number = 4.14159265359

# Convert number into float with 2 decimal

floatNumber = round(number, 2)

print(floatNumber)

Output:

4.14

Example 2:

IIn this example, we start with the string "5.14159265356". We first convert the string to a float using the float() function, and then round it to 2 decimal places using the round() function. Finally, we print the float_number variable, which will output 4.14.

main.py

numberStr = "5.14159265356"

# Convert number into float with 2 decimal

floatNumber = round(float(numberStr), 2)

print(floatNumber)

Output:

5.14

#Python