Precision Handling in Python
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 1: Python code to demonstrate ceil(), trunc() and floor()
In this example, we will cover some 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.
The integral value of number is : 3 The smallest integer greater than number is : 4 The greatest integer smaller than number is : 3
Example 2: How to Limit Floats to Two Decimal Points in Python
In this example, we will see How to Limit Floats to Two Decimal Points in Python. In python float precision to 2 floats in python, and 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 “%”:- “%” 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 decimal part rounded.
The value of number till 2 decimal place(using %) is : 3.45 The value of number till 2 decimal place(using format()) is : 3.453 The value of number till 2 decimal place(using round()) is : 3.45