[toc]
Introduction
Problem Formulation: Given a floating-point value. How to limit it to two decimal places in Python?
Example: Let’s have a look at a program where you have to calculate the value of pi.
import math x = math.pi print("Value of pi is "+ str(x))
Output:
Value of pi is 3.141592653589793
Perfect! pi
yields you a value = 3.141592653589793. But, what if you need the value of pi only up to two decimal places, i.e. 3.14.
Thus, this tutorial will ensure that you know how to limit decimal values to two decimal places. Hence, without further ado, let us dive into the solutions and learn “How to Limit to Two Decimal Points in Python”?
🎥Video Walkthrough
✨Method 1: Using round() function
Before diving into the code/solution, let us quickly understand the significance of the round
method in Python.
✏️ The round() function is an inbuilt function in Python. The function returns a floating-point number that is a rounded version of the specified number. The function has two arguments where the first one is the number to be rounded and the second one is the number of decimal places, i.e. the precision. The precision is set to 0 digits, so round(3.14)
results in 3
.
Syntax: round(number, precision) # rounds the number to the given precision and returns the result
Example:
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)
Output:
x= 3.143667
y= 3
z= 3.144
Related Video:
By now, you must already have an idea about how you can limit a floating value (pi
in this case) to two decimal places. If not, please have a look at the solution given below.
import math x = math.pi print("Value of pi is ", round(x, 2))
Output:
Value of pi is 3.14
? Want to learn more about Built-in methods in Python? Here’s an amazing course for you to master 65 Python Built-in Functions Every Python Coder Must Know!
✨Method 2: Using The format() Function
The format()
function is a built-in method in Python that is used to return a formatted string. The function formats the specific values and inserts them in the placeholder of the string.
Recommended Tutorials to understand how string formatting works in Python:
✒️ Solution: You have to use the format()
method with .2f
placed inside the placeholder that will help to return the value up to two decimal places.
import math x = math.pi print("Value of pi = ", x) print("Value of pi(up to 2 decimal places) = {:.2f}".format(x))
Output:
Value of pi = 3.141592653589793
Value of pi(upto 2 decimal places) = 3.14
✨Method 3: By Using % Formatting
Python’s formatting method uses the modulo operator (the percent sign %
) as a unique symbol to demonstrate the various types of formats. The conversion specifiers, for example, %f
and %s
show up in the format string as placeholders. These specifiers direct how the operation will format the values.
✒️ We will use %.2f
to limit a given floating-point number to two decimal places.
import math x = math.pi print("Value of pi = ", x) print("Value of pi(up to 2 decimal places) = %.2f" % x)
Output:
Value of pi = 3.141592653589793
Value of pi(upto 2 decimal places) = 3.14
✨Method 4: By using f-strings
f-strings are represented by string literals that have an f towards the start and curly braces containing expressions after that. The variables in the expression will get replaced by the values during evaluation at runtime. You have to use f ‘{.2f}’ to return the number up to two decimal places.
import math x = math.pi print("Value of pi = ", x) print(f"Value of pi(up to 2 decimal places) = {x:.2f}")
Output:
Value of pi = 3.141592653589793
Value of pi(up to 2 decimal places) = 3.14
✨Method 5: Using quantize() with Decimal
Interestingly, there is another workaround to our problem. We can import the decimal Decimal
module and utilize its quantize
method to fulfil our goal. When we use the quantize()
method upon the Decimal
, it returns a float value that can be limited up to the desired number of decimal places ( 2 in this case).
The quantize()
method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places. (source: Official Documentation)
Example:
Decimal('7.325635').quantize(Decimal('.001'), rounding=ROUND_DOWN) # Decimal('7.325') Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP) # Decimal('8')
Now, let us have a look at the solution:
from decimal import Decimal import math x = math.pi print("pi = ", x) y = Decimal(x) # Value after limiting the float value to two decimal points using decimal with quantize print("pi (up to 2 decimal places) = ", y.quantize(Decimal('0.01')))
Output:
pi = 3.141592653589793
pi (up to 2 decimal places) = 3.14
Conclusion
Therefore, in this tutorial, you learned about the following methods to limit a given floating-point value to two decimal points in Python:
- Method 1: Using round() function
- Method 2: Using The format() Function
- Method 3: By Using % Formatting
- Method 4: By using f-strings
- Method 5: Using quantize() with Decimal
With that, we come the end of this tutorial. To keep learning and enhance your programming skills, please subscribe to our channel and blog tutorials and stay tuned for more interesting discussions and tutorials. Happy learning!
✍️ Post Credits: Shubham Sayon and Rashi Agarwal
- Do you want to master the most popular Python IDE fast?
- This course will take you from beginner to expert in PyCharm in ~90 minutes.
- For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
Join the PyCharm Masterclass now, and master PyCharm by tomorrow!
Programmer Humor
Q: How do you tell an introverted computer scientist from an extroverted computer scientist?
A: An extroverted computer scientist looks at your shoes when he talks to you.