The Wayback Machine - https://web.archive.org/web/20240610073805/https://www.geeksforgeeks.org/precision-handling-python/
Open In App

Precision Handling in Python

Last Updated : 06 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python in its definition allows handling the precision of floating-point numbers in several ways using different functions. Most of them are defined under the “math” module. In this article, we will use high-precision calculations in Python with Decimal in Python.

Example

Input: x = 2.4
Output: Integral value of no = 2
Smallest integer value = 2
Greatest integer value = 3
Explanation: In this, we are handling precision values in python.

Python Ways to Precision Handling

we will explore the various functions that Python provides for managing precise data and decimal points.

Python Handle Precision using Rounding Method

Python provides for managing precise data and decimal points, the round() function is used to round a number to a specified number of decimal places. Alternatively, string formatting options, such as the f-string syntax or the format() method, allow you to format numbers with precise decimal places.

Python3




rounded = round(8.88888, 2)
print(rounded)
  
formatted = "{:.3f}".format(9.999)
print(formatted)


Output

8.89
9.999

Time Complexity: O(1)
Auxiliary Space: O(1)

Python Handle Precision using Getcontext()

In Python, we can handle precision values using getcontext(). The getcontext() function is used to access the current decimal context, which provides control over precision settings. The precision is used to set the desired number of decimal places for mathematical operations using the decimal class.

Python3




from decimal import Decimal, getcontext
  
getcontext().prec = 3
  
result = Decimal('3') / Decimal('9')
print(result)


Output

0.333

Time Complexity: O(1)
Auxiliary Space: O(1)

Python Handle Precision with Math Module

In Python, we can handle precision values using Math Module. In this example, we will cover some Python math methods. such as trunc() method, ceil() method, and floor() method.

  • trunc() – This function is used to eliminate all decimal parts of the floating-point number and return the integer without the decimal part.
  • ceil() – This function is used to print the least integer greater than the given number.
  • floor() – This function is used to print the greatest integer smaller than the given integer.

Python3




import math
  
a = 3.4536
  
print("The integral value of number is : ", end="")
print(math.trunc(a))
  
# using ceil() to print number after ceiling
print("The smallest integer greater than number is : ", end="")
print(math.ceil(a))
  
# using floor() to print number after flooring
print("The greatest integer smaller than number is : ", end="")
print(math.floor(a))


Output

The integral value of number is : 3
The smallest integer greater than number is : 4
The greatest integer smaller than number is : 3


Time Complexity: O(1)
Auxiliary Space: O(1)

Python Handle Precision with Decimal Module

In Python, we can handle precision values using Decimal Module. In this example, we will see How to Limit Float to Two Decimal Points in Python. In Python float precision to 2 floats in Python, and in Python float precision to 3. There are many ways to set the precision of the floating-point values. Some of them are discussed below.

  • Using % – The % operator is used to format as well as set precision in Python. This is similar to “printf” statement in C programming.
  • Using format() – This is yet another way to format the string for setting precision.
  • Using round(x,n) – This function takes 2 arguments, number, and the number till which we want the decimal part rounded.
  • Using f-string – PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings 

Python3




a = 3.4536
  
print("The value of number till 2 decimal place(using %) is : ", end="")
print('%.2f' % a)
  
# using format() to print value till 3 decimal places
print("The value of number till 3 decimal place(using format()) is : ", end="")
print("{0:.3f}".format(a))
  
# using round() to print value till 2 decimal places
print("The value of number till 2 decimal place(using round()) is : ", end="")
print(round(a, 2))
  
# using f-string to print value till 2 decimal places
print("The value of number till 2 decimal place(using f-string) is : ", end="")
print(f"{a:0,.2f}")


Output

The value of number till 2 decimal place(using %) is : 3.45
The value of number till 3 decimal place(using format()) is : 3.454
The value of number till 2 decimal place(using round()) is : 3.45
The value of number till 2 decimal place(using f-string) is : 3.45

Time Complexity: O(1)
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Setting Precision in Python Using Decimal Module
The decimal module in Python can be used to set the precise value of a number. The default value of the Decimal module is up to 28 significant figures. However, it can be changed using getcontext().prec method. The below program demonstrates the use of decimal module by computing the square root of 2 numbers up to the default the number of places.
1 min read
PyQt5 QDoubleSpinBox – Setting Decimal Precision
In this article we will see how we can set decimal precision of the QDoubleSpinBox. By default decimal precision of double spin box is 2 although we can change it any time. Decimal precision is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a decimal precision of 2. In order to do this we will
2 min read
PyQt5 QDoubleSpinBox – Getting Decimal Precision
In this article we will see how we can get the decimal precision of the QDoubleSpinBox. By default decimal precision of double spin box is 2 although we can change it any time with the help of setDecimals method. Decimal precision is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a decimal pre
2 min read
Precision, Recall and F1-Score using R
Recall, also known as true positive rate (TPR), sensitivity, or hit rate, is a measure of the performance of a binary classification system. It is calculated as the ratio of true positive predictions (i.e., the number of times the model correctly predicted the positive class) to the total number of actual positive cases. In other words, recall is a
4 min read
Handling missing keys in Python dictionaries
In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing keys. Handling Missing Keys in Python DictionariesI
4 min read
SQL using Python | Set 3 (Handling large data)
It is recommended to go through SQL using Python | Set 1 and SQL using Python and SQLite | Set 2 In the previous articles the records of the database were limited to small size and single tuple. This article will explain how to write & fetch large data from the database using module SQLite3 covering all exceptions. A simple way is to execute th
4 min read
Handling PostgreSQL BLOB data in Python
In this article, we will learn how to Handle PostgreSQL BLOB data in Python. BLOB is a Binary large object (BLOB) is a data type that can store any binary data.To store BLOB data in a PostgreSQL database, we need to use the Binary Large Object (BLOB) data type.By using the Binary Large Object (BLOB) data type, we can store any binary data in a Post
5 min read
Multiple Exception Handling in Python
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in th
3 min read
Python | Handling recursion limit
When you execute a recursive function in Python on a large input ( > 10^4), you might encounter a "maximum recursion depth exceeded error". This is a common error when executing algorithms such as DFS, factorial, etc. on large inputs. This is also common in competitive programming on multiple platforms when you are trying to run a recursive algo
4 min read
Python | Handling no element found in index()
Sometimes, while working with Python lists, we are confronted with a problem in which we need to check whether an element is present in a list and also where exactly, which index it occurs. The convenient solution of it is to use index(). But problem with this can come that sometimes, the desired element might not be present in the list. Let's disc
5 min read
Article Tags :
Practice Tags :