How to Limit Floats to Two Decimal Points in Python

Created
Modified

Using format Method

You can use str.format() function to limit floats, it really simple. For example,

#!/usr/bin/python3
# -*- coding: utf8 -*-

f = 13.949999999999999
print("{:.2f}".format(f))
print(format(f, '.2f'))

# to float
print(float("{:.2f}".format(f)))
13.95
13.95
13.95

Using F-strings

F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value.

#!/usr/bin/python3
# -*- coding: utf8 -*-

a = 13.949999999999999
print(f'{a:.2f}')
a = 2.675
print(f'{a:.2f}')
a = 2.675222
print(f'{a:.2f}')
13.95
2.67
2.68

Using round Method

Round a number to a given precision in decimal digits. If ndigits is omitted or is None, it returns the nearest integer to its input.

For example,

#!/usr/bin/python3
# -*- coding: utf8 -*-

print(round(13.949999999999999, 2))
print(round(2.675, 2))
print(round(2.675222, 2))
print(round(1.5, 2))
print(round(1.5))
13.95
2.67
2.68
1.5
2

Another form of exact arithmetic is supported by the fractions module which implements arithmetic based on rational numbers (so the numbers like 1/3 can be represented exactly).

Using int Method

You can do the same as:

#!/usr/bin/python3
# -*- coding: utf8 -*-

f = 13.949999999999999

b = int(f*100 + 0.5) / 100.0
print(b)

f = 2.675
b = int(f*100 + 0.5) / 100.0
print(b)
13.95
2.68

Related Tags

#limit# #float# #point#