📜  python3 print format float - Python (1)

📅  最后修改于: 2023-12-03 14:46:19.943000             🧑  作者: Mango

Python3 Print Format Float

In Python, the print() function is commonly used to display data on the console. When working with floating-point numbers, it is important to format the output to a specific number of decimal places or scientific notation as desired. This guide will introduce different ways to format float values using the print() function in Python 3.

Basic print() Syntax

The basic syntax of the print() function in Python is:

print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  • value1, value2, ...: It represents the values or variables that need to be printed to the console. Multiple values can be separated by commas.
  • sep=' ': It is an optional parameter that specifies the separator between the values. By default, it is set to a space character.
  • end='\n': It is an optional parameter that defines the string appended after all values have been printed. By default, it is set to a newline character.
  • file=sys.stdout: It is an optional parameter that specifies the file object where the output will be written. By default, it is set to standard output, i.e., sys.stdout.
  • flush=False: It is an optional parameter that determines if the output buffer should be flushed immediately. By default, it is set to False.
Formatting Floats with Precision

Python provides the format() function to format floating-point numbers with a specific precision. The general syntax to format a floating-point number num is:

print('{:.nf}'.format(num))
  • n is the desired number of decimal places.

Example:

pi = 3.141592653589793
print('{:.2f}'.format(pi))  # Output: 3.14

We use :.2f inside the placeholder {} to specify that the floating-point number should be rounded to 2 decimal places.

Using String Formatting

Another way to format floating-point numbers is using string formatting. The % operator can be used for this purpose.

print('%.nf' % (num,))
  • Again, n is the desired number of decimal places.

Example:

pi = 3.141592653589793
print('%.2f' % (pi,))  # Output: 3.14

In this example, we use %.2f to format pi with 2 decimal places.

Scientific Notation

To display a floating-point number in scientific notation, we can use either the e or E format specifier.

print('{:e}'.format(num))

Example:

num = 1234000000.0
print('{:e}'.format(num))  # Output: 1.234000e+09
Conclusion

By using the format() function or string formatting with the % operator, Python programmers can easily format floating-point numbers to their desired precision or in scientific notation. These techniques provide flexibility and control over how float values are displayed when printing in Python 3.