Restrict floats to two decimal points in Python
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:
|
1 2 3 4 |
pi = 3.141592653589793238 print(round(pi, 2)) # 3.14 |
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:
|
1 2 3 4 |
pi = 3.141592653589793238 print(format(pi, '.2f')) # 3.14 |
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:
|
1 2 3 4 |
pi = 3.141592653589793238 print("{:.2f}".format(pi)) # 3.14 |
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:
|
1 2 3 4 5 |
import decimal pi = 3.141592653589793238 print(decimal.Decimal(pi).quantize(decimal.Decimal("0.01"))) # 3.14 |
5. Using % conversion
Finally, we may use the % conversion to produce a string rounded to two decimal points. Here is an example:
|
1 2 3 4 |
pi = 3.141592653589793238 print("%.2f" % pi) # 3.14 |
That’s all about restricting floats to two decimal points in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)