When writing software in Python, you might occasionally need to adjust the number of decimal places shown for a numeric value.
By default, Python rounds float values to the closest number with decimal precision of two digits. However, as we will see, Python offers several methods for displaying floats with more decimal precision. In this tutorial, you’ll learn how to increase decimal places in Python.
Step 1: Using the Round Function
One common method for managing decimal places is the built-in Python function, round(). This function works by taking two arguments: the number you want to round, and the number of decimal places to which you want to round this number. If you omit the second argument, Python rounds the number to the nearest integer.
number = 5.6789 rounded_number = round(number, 3) print(rounded_number)
The output is:
5.679
Step 2: Using the Format Function
An alternative method for managing decimal places is to use Python’s built-in format() function. This function allows you to control number formatting in a more detailed manner.
number = 5.6789 printed_number = "{:.3f}".format(number) print(printed_number)
The output is:
5.679
Step 3: Using String Formatting (f-Strings)
In Python 3.6 and above, one of the ways to format strings, and therefore control decimal places, is to use the so-called f-strings. Just like the format() function, f-strings offer a concise syntax for embedding expressions inside string literals.
number = 5.6789 printed_number = f"{number:.3f}" print(printed_number)
The output is:
5.679
Here’s the full context of the code:
number = 5.6789 rounded_number = round(number, 3) print(rounded_number) printed_number = "{:.3f}".format(number) print(printed_number) printed_number = f"{number:.3f}" print(printed_number)
Conclusion
In this tutorial, you’ve learned three different methods for increasing the number of decimal places in Python: using the round function, the format function, and f-strings.
Hopefully, you now have a strong understanding of each of these methods and are comfortable implementing them in your Python codebase whenever you need more fine-grained control over numeric precision.