How To Print Float In Python

In this tutorial, you will learn how to print float values in Python. Handling float values is essential when working with numerical data, as floating-point values represent real numbers that can hold both integers and non-integer values which we often encounter in calculations and data manipulation.

Step 1: Understanding floating-point numbers in Python

Floating-point numbers or floats are used to represent real numbers that can hold both integer and non-integer values. They are written either in decimal notation (0.1, 1.23, etc.) or in scientific notation (1.5e-3, 3.1e5, etc.). In Python, floats are stored and manipulated using the built-in float data type.

Here’s an example of a simple float value:

Output:

3.14

Step 2: Using the print() function to display float values

In Python, you can use the **print()** function to display the value of a float variable. By default, Python will print the float value without any formatting:

Output:

3.14
9.81

Step 3: Formatting float values using format strings

Python supports a very powerful technique called format strings. This can be used to format the string representation of your float values to control the number of decimal points, how the float is displayed, and other settings.

The most common way to format float values using format strings is to use the str.format() method of a string:

Output:

3.14

In the example above, the format string is “{:.2f}”. The “:” is used to separate the text before and after the formatting, the “.2” indicates the precision (number of decimal points) required and the “f” is used to specify that the value should be treated as a float.

Step 4: Using f-strings to format float values

Starting from Python version 3.6, there is a more convenient way to format float values called “f-strings”. F-strings allow you to include expressions inside string literals, using curly braces “{}”. You can use the same formatting options as in format strings:

Output:

3.14

Full code

Output:

3.1415926535
9.81
3.14
9.810
3.14
9.810

Conclusion

In this tutorial, you have learned how to print and format float values in Python using the print() function, format strings, and f-strings. These techniques can be used to display float values with a specific number of decimal places or any other desired formatting in your Python programs.