I need to round floating number in such a way that,
If 7.4 comes, it should round to next lower number, that is 7.
If 7.5 or 7.6 comes it should round to next higher number, that is 8
How can I do that? I am using python 2.7
I need to round floating number in such a way that,
If 7.4 comes, it should round to next lower number, that is 7.
If 7.5 or 7.6 comes it should round to next higher number, that is 8
How can I do that? I am using python 2.7
You can use the round()
function which comes builtin in python (https://docs.python.org/2/library/functions.html#round)
>>> round(7.4)
7
>>> round(7.5)
8
From the documentation:
Note the behaviour of
round()
for floats can be surprising: for example,round(2.675, 2)
gives2.67
instead of the expected2.68
. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
You want to use the round() builtin.
You haven't specified whether or not you are using Python 2 or 3, but note that in Python3, round()
does bankers rounding: https://docs.python.org/3/library/functions.html#round.
You can use the round() method for this. The round() method takes two parameters. round(a, b). a is the the floating number whereas b is the number of decimal places up to which you want.
print round(60.23456, 2)
will give you an answer of 60.23
P.S This is python 2.7
In python 3 you can use
math.ceil(x) or math.floor(x)
for more information go to https://docs.python.org/3/library/math.html
Hope this helps :)