How to limit decimal places in python

TLDR ;)

The rounding problem of input and output has been solved definitively by Python 3.1 and the fix is backported also to Python 2.7.0.

Rounded numbers can be reversibly converted between float and string back and forth:
str -> float() -> repr() -> float() ... or Decimal -> float -> str -> Decimal

>>> 0.3
0.3
>>> float(repr(0.3)) == 0.3
True

A Decimal type is not necessary for storage anymore.

Results of arithmetic operations must be rounded again because rounding errors could accumulate more inaccuracy than that is possible after parsing one number. That is not fixed by the improved repr() algorithm (Python >= 3.1, >= 2.7.0):

>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1, 0.2, 0.3
(0.1, 0.2, 0.3)

The output string function str(float(...)) was rounded to 12 valid digits in Python < 2.7x and < 3.1, to prevent excessive invalid digits similar to unfixed repr() output. That was still insufficientl after subtraction of very similar numbers and it was too much rounded after other operations. Python 2.7 and 3.1 use the same length of str() although the repr() is fixed. Some old versions of Numpy had also excessive invalid digits, even with fixed Python. The current Numpy is fixed. Python versions >= 3.2 have the same results of str() and repr() function and also output of similar functions in Numpy.


Test

import random
from decimal import Decimal
for _ in range(1000000):
    x = random.random()
    assert x == float(repr(x)) == float(Decimal(repr(x)))  # Reversible repr()
    assert str(x) == repr(x)
    assert len(repr(round(x, 12))) <= 14         # no excessive decimal places.

Documentation

See the Release notes Python 2.7 - Other Language Changes the fourth paragraph:

Conversions between floating-point numbers and strings are now correctly rounded on most platforms. These conversions occur in many different places: str() on floats and complex numbers; the float and complex constructors; numeric formatting; serializing and de-serializing floats and complex numbers using the marshal, pickle and json modules; parsing of float and imaginary literals in Python code; and Decimal-to-float conversion.

Related to this, the repr() of a floating-point number x now returns a result based on the shortest decimal string that’s guaranteed to round back to x under correct rounding (with round-half-to-even rounding mode). Previously it gave a string based on rounding x to 17 decimal digits.

The related issue


More information: The formatting of float before Python 2.7 was similar to the current numpy.float64. Both types use the same 64 bit IEEE 754 double precision with 52 bit mantissa. A big difference is that np.float64.__repr__ is formatted frequently with an excessive decimal number so that no bit can be lost, but no valid IEEE 754 number exists between 13.949999999999999 and 13.950000000000001. The result is not nice and the conversion repr(float(number_as_string)) is not reversible with numpy. On the other hand: float.__repr__ is formatted so that every digit is important; the sequence is without gaps and the conversion is reversible. Simply: If you perhaps have a numpy.float64 number, convert it to normal float in order to be formatted for humans, not for numeric processors, otherwise nothing more is necessary with Python 2.7+.

  • Introduction
  • 🎥Video Walkthrough
  • ✨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 
  • Conclusion
  • Programmer Humor

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

How to Limit Floats to Two Decimal Points in Python?

✨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:

Python round() — A Helpful Interactive Guide

Python round()

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:

  • String Formatting: Keep It Simple
  • String Formatting Comparison: format() | Percent | f-string

✒️ 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.

How to limit decimal places in python

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork
LinkedIn

How do you keep 2 decimal places in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

How do I keep 3 decimal places in Python?

“how to print value to only 3 decimal places python” Code Answer's.
print(format(432.456, ".2f")).
>> 432.45..
print(format(321,".2f")).
>> 321.00..

How do I keep 4 decimal places in Python?

“how to round to 4 decimal places in python” Code Answer's.
a_list = [1.234, 2.345, 3.45, 1.45].
round_to_whole = [round(num) for num in a_list].
print(round_to_whole).

How do you limit decimal places to 2?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.