Float to 3 decimal places as a string
Write a Python program to format a float to 3 decimal places and convert it to a string.
2.14652
2.147 str
Approach
- Use the format spec
.3f.
Solution
x = 2.14652text = f"{x:.3f}"print(text, type(text).__name__)2.147 str
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.
Learn the concept
New to this topic? Read the lesson, then come back.