How to Convert String to Float with 2 Decimal Places in Python?

13-Jun-2023

.

Admin

How to Convert String to Float with 2 Decimal Places in Python?

Hi Dev,

This article will provide some of the most important examples of Python converting string to float with 2 decimal places. let’s discuss the Python string to 2 decimal places. This article will give you a simple example of a Python string to float 2 decimals. let’s discuss Python format string to 2 decimal places. Let's get started with Python print string to 2 decimal places.

You can convert a string 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 string "3.12159265359". 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 = "3.12159265359"

# Convert number into float with 2 decimal

floatNumber = round(float(numberStr), 2)

print(floatNumber)

Output:

3.12

Example 2:

In this example, we start with the number 5.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 = 5.14159265359

# Convert number into float with 2 decimal

floatNumber = round(number, 2)

print(floatNumber)

Output:

5.14

#Python