Round a floating-point number to the nearest integer?

As the name implies, I want to take a floating point number and round it to the nearest integer. However, if it is not an integer, I ALWAYS want to round a variable, no matter how close it is to the next integer. Is there any way to do this?

+49
python floating-point integer rounding number-rounding
Jun 17 '13 at 7:00
source share
10 answers

Plain

print int(x) 

will also work.

+77
Jun 17 '13 at 7:51 on
source share

One of them should work:

 import math math.trunc(1.5) > 1 math.trunc(-1.5) > -1 math.floor(1.5) > 1 math.floor(-1.5) > -2 
+45
Jun 17 '13 at 7:05
source share

I think you need the gender function:

math.floor (x)

+16
Jun 17 '13 at 7:04 on
source share

To get a floating point result, simply use:

 round(x-0.5) 

It also works for negative numbers.

+11
Apr 15 '15 at 13:22
source share

If you do not want to import math, you can use:

int(round(x))

Here is a piece of documentation:

 >>> help(round) Help on built-in function round in module __builtin__: round(...) round(number[, ndigits]) -> floating point number Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative. 
+5
May 29 '14 at 22:12
source share

Many say what to use:

  int(x) 

and this works fine for most cases, but there is a small problem. If the result is OP:

  x = 1.9999999999999999 

it will be rounded to

  x = 2 

after the 16th 9th round. This is not a big deal if you are sure you will never encounter such a situation. But this is something to keep in mind.

+5
Jul 02 '15 at 10:15
source share

It can be very simple, but could you just round it down to minus 1? For example:

 number=1.5 round(number)-1 > 1 
+1
May 16 '14 at 17:41
source share

If you work with numpy, you can use the following solution, which also works with negative numbers (it also works with arrays)

 import numpy as np def round_down(num): if num < 0: return -np.ceil(abs(num)) else: return np.int32(num) round_down = np.vectorize(round_down) 



 round_down([-1.1, -1.5, -1.6, 0, 1.1, 1.5, 1.6]) > array([-2., -2., -2., 0., 1., 1., 1.]) 

I think this will also work if you just use the math module instead of the numpy module.

+1
Jun 22 '16 at 21:34
source share
 x//1 

The // operator returns the division field. Since dividing by 1 does not change your number, this is equivalent to gender, but import is not required. You will not get the int that was returned.

+1
Nov 11 '17 at 4:13
source share

I donโ€™t know if you decided this, but I just stumbled upon this question. If you want to get rid of decimal points, you can use int (x) and eliminate all decimal digits. No need to use round (x).

0
Nov 28 '14 at 7:20
source share



All Articles