Python Practice › String Programs › Program 41

Float to 3 decimal places as a string

EasyString Programs · 41 of 106

Write a Python program to format a float to 3 decimal places and convert it to a string.

Advertisement
Input
2.14652
Output
2.147 str

Approach

  1. Use the format spec .3f.

Solution

Python
x = 2.14652text = f"{x:.3f}"print(text, type(text).__name__)
Output
2.147 str
Note

Formatting rounds, so 2.14652 becomes “2.147”, not “2.146” as the original sample showed. Use str(int(x * 1000) / 1000) if you need to cut off digits instead.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs