When displaying floating-point numbers (float) in Python using print(), they are usually automatically rounded to a readable length. However, in scientific computing or debugging, you may want to display more digits (or a specific number of digits).
This article explains how to finely control the display precision of floating-point numbers using the format() function and f-strings.
Specifying the Number of Decimal Places
To specify the display format for floating-point numbers, use the format specifier .{digits}f.
1. Using f-strings (Recommended)
In Python 3.6 and later, using f-strings is the most concise method. You simply add a colon : followed by the format specifier after the variable name.
Syntax: f"{value:.{digits}f}"
import math
# Pi (3.1415926535...)
pi_value = math.pi
# Default display
print(f"Default: {pi_value}")
# 2 decimal places
print(f"2 digits: {pi_value:.2f}")
# 10 decimal places
print(f"10 digits: {pi_value:.10f}")
# 50 decimal places (checking precision limit)
print(f"50 digits: {pi_value:.50f}")
Execution Result:
Default: 3.141592653589793
2 digits: 3.14
10 digits: 3.1415926536
50 digits: 3.14159265358979311599796346854418516159057617187500
2. Using the format() Function
You can achieve the same result using the built-in format() function.
Syntax: format(value, ".{digits}f")
number = 1 / 7
print(f"Value: {number}")
# Display 20 decimal places
formatted_str = format(number, ".20f")
print(f"20 digits: {formatted_str}")
Execution Result:
Value: 0.14285714285714285
20 digits: 0.14285714285714284921
Checking Floating-Point Errors
Python’s float is typically implemented as a 64-bit double-precision floating-point number, which has about 15 to 17 significant digits. Therefore, if you increase the number of display digits extremely, you may visualize internal “calculation errors” or “values that cannot be represented.”
For example, the number 0.3 cannot be represented exactly in binary, so expanding the digits reveals its actual state.
val = 0.3
print(f"Normal: {val}")
print(f"30 digits: {val:.30f}")
Execution Result:
Normal: 0.3
30 digits: 0.299999999999999988897769753748
Although it normally displays as 0.3, internally it is held as an approximate value like 0.2999.... When debugging why calculations do not match, it is effective to increase the display digits like this to verify the actual value.
Summary
- To control float precision, use
:.nfin f-strings orformat(val, ".nf"). - Specify the number of decimal places in
n(e.g.,.2ffor 2 digits). - Increasing the number of digits allows you to check for minute errors specific to floating-point numbers.
