# Precision Handling in Python

In Python, we have different types of data types like boolean, integer, lists and float. Python has different functions to handle different data types. To handle the precision in the float data type, Python mostly uses the ‘math’ module. In this tutorial, we will be discussing some common methods of Python’s math module and some different methods to set precision in Python.

## How to do Precision Handling in Python

First We will import the math module.

import math

Now we will see different methods.

- trunc(): This method removes the fraction part from a floating-point number. It returns the integer part of the number.
**ceil()**: This method is used to return the ceiling number of the floating-point number. The ceiling number is the smallest integer greater than the number.**floor()**: This method is used to return the floor number of the floating-point number. The floor number is the greatest integer smaller than the number.

import math number = 109.897 print('Truncated value: ' + str(math.trunc(number))) print('Ceiling Value: ' + str(math.ceil(number))) print('Floor Value: ' + str(math.floor(number)))

Output:

Truncated value: 109 Ceiling Value: 110 Floor Value: 109

Till now we have seen the cod to remove the fraction part altogether. Now we will see how to manipulate the decimal part.

**The %****operator**: It is used to format and set precision. It is like the printf in C language.**format()**: It is another way to format the string and set precision.**round(n,d)**: It is to round off the number n up to d decimal places.

import math number = 109.876543 print('Value upto 2 decimal places is %.2f' %number) print('Value upto 3 decimal places is {0:.3f}'.format(number)) print('Round Value upto 3 decimal places is ' + str(round(number, 3)))

Output

Value upto 2 decimal places is 109.88 Value upto 3 decimal places is 109.877 Round Value upto 3 decimal places is 109.877

So in conclusion, These are six basic methods to manipulate floating-point numbers.

## Leave a Reply