Round in python
April 7, 2016, 8:05 p.m.
There is a
round(number, ndigits) function for rounding of numbers, where
number is required number for rounding,
ndigits is a number of simbols after comma. For example:
round(2.137, 2) # = 2.14
Round function has some feature that consists in the fact that it works on the principle of bank rounding to round off the numbers in which the last five is a sign, for example:
round(2.05, 1) # = 2.0 round(2.15, 1) # = 2.1 round(2.25, 1) # = 2.3 round(2.35, 1) # = 2.4 round(2.45, 1) # = 2.5 round(2.55, 1) # = 2.5 round(2.65, 1) # = 2.6 round(2.75, 1) # = 2.8 round(2.85, 1) # = 2.9 round(2.95, 1) # = 3.0
Rounding is performed on a special principle. I tell why it is so. Banking (or accounting) rounding allows you to reduce errors when working with a large array of data. Ordinary (or arithmetic) rounding gives an increasing error due to the fact that rounding down should have at the end numbers: 1, 2, 3, 4 - only 4 digits, and in large: 5, 6, 7, 8, 9 - only 5 digits. An uneven number of digits and cause an increasing error in the calculations. A bank rounding works according to statistical laws: the probability that the five will be an even or odd number about the same, so this principle reduces the error.
In python the rounding to ceiling value (to upwards)
math.ceil(x) - the smallest integer not less than
And the rounding to floor value (to downwards)
math.floor(x) - the largest integer not greater than
import math math.ceil(2.3) # = 3.0 math.floor(2.7) # = 2.0
For getting a integer number you should use
round(2.6) # = 3.0 int(round(2.6)) # = 3
For getting rid of symbols after comma you can do so:
int(2.6) # = 2 , is equal to int(math.floor(2.6))
Do you need to develop yourself or do you want to earn money?
Are you looking for good IT services or books? Save your time and look at my compilation of recommendations, which I use every day.
Go to recommendations