Python print float: How to Print Float Values in Python

If you define a value without decimals, Python will interpret it as an integer, and if you specify values that include decimals will be interpreted as floating-point numbers.

What is float in Python?

Python float is a data type that represents a floating-point number. A floating-point number is a number with a decimal point, such as 3.14 or 2.718.

data = 19.21

print(type(data))

Output

<class 'float'>

Python print float

To print float values in Python, use the print() function. The print() is a built-in function that prints the defined message to the screen or standard output device like a Python console. It takes a float as its argument and prints it to the standard output stream.

To print float values with two decimal places in Python, use the str.format() with “{:.2f}” as str. The str.format() function formats the specified value and insert 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

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.

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

We can see that we printed a float value with four decimal places.

Printing a list of float values in Python

To print a list of float values in Python, use the list comprehension with “%.2f”.

data_list = [1.1111, 2.1134, 2.444444, 9.00022]

float_values = ["%.2f" % x for x in data_list]
print(float_values)

Output

['1.11', '2.11', '2.44', '9.00']

All the values are converted into two decimal-place values.

Conclusion

The print() is a built-in function that makes it easy to print a float 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.

That’s it for this tutorial.

Leave a Comment