This post will discuss how to restrict floats to two decimal points in Python.

1. Using round() function

A simple solution to restrict floats to two decimal points is using the built-in function round(x[, n]). It returns number x rounded to n digit precision after the decimal point. For example, we can restrict the pi to two decimal points by passing it as the first argument and the number 2 as the second argument to the round() function:

Download  Run Code

2. Using format() function

The built-in function format() outputs the float as a string, rounded according to the specified format specification. We can use it to restrict floats to two decimal points by using a format specifier that indicates two digits after the decimal point. For example, we can restrict the float of 3.14159 to two decimal points using the format() function like this:

Download  Run Code

3. Using str.format() function

Another solution is to perform a string formatting operation using the str.format() function. We can use it to restrict floats to two decimal points by creating a string with a placeholder "{:.2f}" that indicates two digits after the decimal point and passing the float as an argument. For example:

Download  Run Code

4. Using decimal module

We can use decimal module to restrict floats to two decimal points by creating a decimal.Decimal object from the float and using the quantize() function, which rounds a number to a fixed exponent according to a given rounding mode. For example:

Download  Run Code

5. Using % conversion

Finally, we may use the % conversion to produce a string rounded to two decimal points. Here is an example:

Download  Run Code

That’s all about restricting floats to two decimal points in Python.