Precision Handling in Python

PythonProgrammingServer Side Programming

Python can handle the precision of floating point numbers using different functions. Most functions for precision handling are defined in the math module. So to use them, at first we have to import the math module, into the current namespace.

import math

Now we will see some of the functions for precision handling.

The trunc() function

The trunc() method is used to remove all fractional part from a floating point number. So it returns only the integer part from the number.

The ceil() function

The ceil() method is used to return the Ceiling value of a number. The Ceiling value is the smallest integer, which is greater than the number.

The floor() function

The floor() method is used to return the Floor value of a number. The Floor value is the largest integer, which is smaller than the number.

Example code

Live Demo

import math
number = 45.256
print('Remove all decimal part: ' + str(math.trunc(number)))
print('Ceiling Value: ' + str(math.ceil(number)))
print('Floor Value: ' + str(math.floor(number)))

Output

Remove all decimal part: 45
Ceiling Value: 46
Floor Value: 45

As we have seen, using the mentioned functions, we can remove the decimal part and get the exact integer. Now we will see how to manage the decimal part using more effective way.

The %Operator

The % operator is used to format and set precision in Python.

The format() function

The format() method is also used to format the string to setup the correct precision

The round(a, n) function

The round() method is used to round off the number a, up to n decimal places

Example code

Live Demo

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

Output

Value upto 3 decimal places is 45.257
Value upto 4 decimal places is 45.2566
Round Value upto 3 decimal places is 45.257
raja
Published on 23-Nov-2018 13:27:32
Advertisements