-4

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

abarisone
  • 3,707
  • 11
  • 35
  • 54
Akhil Mathew
  • 1,571
  • 3
  • 34
  • 69

4 Answers4

5

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) gives 2.67 instead of the expected 2.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.

Adriano
  • 3,788
  • 5
  • 32
  • 53
  • 3
    Caveat: `round(8.5)` will give you a result of `9` in Python 2 and `8` in Python 3. Keep this in mind if you ever want to switch to Python 3. – Matthias Jun 30 '16 at 06:30
3

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.

Maltysen
  • 1,868
  • 17
  • 17
1

You can use round:

>>> round(7.4)
7
>>> round(7.5)
8
niemmi
  • 17,113
  • 7
  • 35
  • 42
1

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 :)

Satyaki Sanyal
  • 1,201
  • 11
  • 12