To print float values in Python, you can use the print() function. Another way is to use the str.format() function with “{:.2f}” as str, which formats the float value with two decimal places. The str.format() function formats the specified value and inserts them inside the string’s placeholder. Then use the print() function with the formatted float-string as a string to print the float values.
Syntax
print("{:.2f}".format(float_values))
Example 1
float_val = 19.211146
formatted_float_value = "{:.2f}".format(float_val)
print(formatted_float_value)
Output
19.21
In this example, we use the format() method of the str class to format the float as a string with two decimal places.
We pass the format string ‘{:.2f}’ as the argument to the format() method specifies that the float should be formatted with two decimal places.
We then pass the float as the argument to the print() function, which prints the formatted float to the standard output stream.
Example 2
To get a float value with four decimal places, you should use “{:.4f}”. The format() method returns the formatted string.
float_val = 19.211146
formatted_float_value = "{:.4f}".format(float_val)
print(formatted_float_value)
Output
19.2111
Conclusion
You can use the print() function to print the float values in Python. To print a float with a specific number of decimal places, use the str.format() method to format the float as a string.