W3docs

Limiting floats to two decimal points

To limit a float to two decimal points, you can use the round() function.

To limit a float to two decimal points, you can use the round() function. This function rounds a number to a specified number of decimal places. Note that Python uses banker's rounding (round half to even), so values exactly halfway between two numbers are rounded to the nearest even number.

Here is an example:

Limit a float to two decimal points, using the round() function

x = 3.14159265
y = round(x, 2)
print(y)

This will print 3.14, as y has been rounded to two decimal places and remains a float.

You can also use the format() function to achieve the same visual result. Note that format() returns a string, not a float. You can use the :.2f format specifier to specify that you want a float with two decimal places.

Here is an example:

Limit a float to two decimal points, using the format() function

x = 3.14159265
y = format(x, '.2f')
print(y)

This will also print 3.14, but y is now a string.

If you want to actually change the value of the variable itself, rather than just printing it, you can use either approach in an assignment statement. For example:

Limit a float to two decimal points, using the round() function, and reassign the value

x = 3.14159265
x = round(x, 2)
print(x)

or

Limit a float to two decimal points, using the format() function, and reassign the value

x = 3.14159265
x = format(x, '.2f')
print(x)

This will change the value of x to 3.14. With round(), x remains a float. With format(), x becomes a string.