Skip to content

Python string format float | Example code

  • by

The given float() is a built-in function having a single parameter format specifier “%” to print floats to a specific number of decimal points in Python.

"%.2f" % float_num

The format() function formats the specified value(s) and inserts them inside the string’s placeholder. The placeholder is defined using curly​ The format() method formats the specified value(s) and inserts them inside the string’s placeholder.

str.format(value)

Python string format float example

Simple example code of string Print floats to a specific number of decimal points in Python.

Use str.format() to format a floating number

Format to 2 decimal places.

pi = 3.14159265359

my_formatter = "{0:.2f}"

res = my_formatter.format(pi)

print(res)

Output:

Python string format float

With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.

pi = 3.14159265359

# Option one
older_method_string = "%.5f" % pi
print(older_method_string)

# Option two
newer_method_string = "{:.5f}".format(pi)
print(newer_method_string)

Output:

3.14159
3.14159

Do comment if you have any doubts or suggestions on this Python format topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *