Skip to content

Python float precision to 2

  • by

You can use multiple ways to float precision to 2 decimal points in Python. A simple way is used str.format(number) with .2f inside the placeholder, i.e., {:.2f} . This returns a string representation of the number up to two decimal places.

  • str.format(): that formats specific values and inserts them in the placeholder {} of the string and returns the formatted string.
  • f-string (String Literal): that has the prefix ‘f‘ containing expressions inside curly braces.
  • % formatting: modulo operator (the percent sign %) as a unique symbol to demonstrate the various types of formats.
string.format(value1, value2...)

#OR
f'{value: .2f}'

#OR

Python float precision to 2 example

Simple example code print to 2 decimal places.

import math

radius = 5
area = math.pi * radius * radius
print("Area = ", area)

# format
print("Area = {:.2f}".format(area))

# f-string
print(f"Area = {area:.2f}")

# % formatting
print("Area = %.2f" % area)

Output:

Python float precision to 2

Using round() function

x = 3.143667
y = round(x)
z = round(x, 3)  # Limit the float value to three decimal points
print("x=", x)
print("y=", y)
print("z=", z)

Using quantize() with Decimal

This returns a float value that can be limited up to the desired number of decimal places ( 2 in this case).

Decimal('7.325635').quantize(Decimal('.001'), rounding=ROUND_DOWN)
# Decimal('7.325')
Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
# Decimal('8')

Do comment if you have any doubts or suggestions on this Python float 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading