NumPy Rounding Off
Submitted by moazkhan on Sunday, July 12, 2020 - 12:34.
In this tutorial you will learn:
- What is rounding off the decimal?
- Python functions that could round off the decimals?
- Python Syntax
Rounding off the decimals
Rounding off is a simple technique for conversion of float numbers to integers, however, the resultant value will be less accurate (as we remove the part after decimal), but easier to use. The data in type of most of the arrays as a programmer we will be encountering while coding in python will be the integers and floats. Number of times programmers have to round off the float numbers and convert them to integers. It is a very common process, either the float number can be rounded off to the floor value or the ceil value, it is totally dependent on the requirement of the programmerPython Functions for Rounding Off
Python provides the following functions for rounding off the float numbers.- Floor
- Ceil
- Fix
- Around
- Trunc
- #importing the numpy lib
- import numpy as np
- #applying the floor function on 1.88 and 1.11 separately
- res1 = np.floor(1.88)
- res2 = np.floor(1.11)
- print('Result of Rounding off 1.88 using floor() function: ', res1)
- print('Result of Rounding off 1.11 using floor() function: ', res2)
In this example we will be rounding off the float numbers using ceil() function, in the results you can observe that whatever value we write after the decimal point, the number will be rounded to the nearest greater integer.
- #importing the numpy lib
- import numpy as np
- #applying the floor function on 2.99 and 2.01 separately
- res1 = np.ceil(2.99)
- res2 = np.ceil(2.01)
- print('Result of Rounding off 2.99 using ceil() function: ', res1)
- print('Result of Rounding off 2.01 using ceil() function: ', res2)
- #importing the numpy lib
- import numpy as np
- #applying the fix() function on 4.15 and 4.92 separately
- res1 = np.fix(4.15)
- res2 = np.fix(4.92)
- print('Result of Rounding off 4.15 using fix() function: ', res1)
- print('Result of Rounding off 4.92 using fix() function: ', res2)
- #importing the numpy lib
- import numpy as np
- #applying the around function on 5.45 and 5.52 separately
- res1 = np.around(5.45)
- res2 = np.around(5.52)
- print('Result of Rounding off 5.45 using around() function: ', res1)
- print('Result of Rounding off 5.52 using around() function: ', res2)
- #importing the numpy lib
- import numpy as np
- #applying the truncate function on 8.11 and 8.75 separately
- res1 = np.trunc(8.11)
- res2 = np.trunc(8.75)
- print('Result of Rounding off 8.11 using trunc() function: ', res1)
- print('Result of Rounding off 8.75 using trunc() function: ', res2)
Add new comment
- 152 views