How to limit float values to N decimal places in Python

Pratik Choudhari

A float data type is a numeric data type with decimal places. In some cases, float values can go to hundreds of decimal places. Therefore, we need to truncate the value to view only the first N decimal places.

This article will show how we can limit a float number to N decimal places using a format specifier.

What are format specifiers?

Format specifiers define how data is to be printed on standard output, it includes doing operations like truncating values and extending values.

All major programming languages have this feature.

Limiting decimal places in Python

The format specifier we need here is .Nf where N is the number of decimal places expected in output.

There are two ways to implement this, the first is using f-strings and the second is using the format property of strings.

Using f-strings

number = 3.142857142857143 print("f"{number:.2f}") print("f"{number:.3f}")


3.14 3.143

Using format property

number = 3.142857142857143 print("{:.2f}".format(number))



If you need more precise precision handling, you can learn more in this article.

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses