In addition to the basic formatting techniques, Python provides more advanced options for formatting floating-point numbers. These techniques can be particularly useful when dealing with large or small numbers, or when you need to control the overall appearance of the output.
Scientific Notation
To display a floating-point number in scientific notation, you can use the e
or E
format specifier. This is useful for very large or very small numbers:
x = 123456.789
print(f"{x:0.2e}") ## Output: 1.23e+05
print(f"{x:0.2E}") ## Output: 1.23E+05
Padding and Alignment
You can also control the width and alignment of the output using additional formatting options. For example, to right-align a number with a minimum width of 10 characters:
x = 3.14159
print(f"{x:10.2f}") ## Output: 3.14
To left-align the number:
x = 3.14159
print(f"{x:<10.2f}") ## Output: 3.14
You can also add leading zeros to the output:
x = 3.14159
print(f"{x:010.2f}") ## Output: 0000003.14
To display a floating-point number with thousands separators (e.g., commas), you can use the ,
format specifier:
x = 1234567.89
print(f"{x:,.2f}") ## Output: 1,234,567.89
This can be particularly useful when working with large numbers.
You can combine multiple formatting options to achieve the desired output. For example, to display a number with a minimum width of 15 characters, 4 decimal places, and thousands separators:
x = 1234567.89
print(f"{x:15,.4f}") ## Output: 1,234,567.8900
By mastering these advanced formatting techniques, you can create highly customized and readable output for your floating-point numbers in Python.