I\'ve been trying to round long float numbers like:
32.268907563;
32.268907563;
31.2396694215;
33.6206896552;
...
With no success so far. I
Your solution is calling round without specifying the second argument (number of decimal places)
>>> round(0.44)
0
>>> round(0.64)
1
which is a much better result than
>>> int(round(0.44, 2))
0
>>> int(round(0.64, 2))
0
From the Python documentation at https://docs.python.org/3/library/functions.html#round
round(number[, ndigits])
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
Note
The behavior 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.
Some thing like this should also work
import numpy as np
def proper_round(a):
'''
given any real number 'a' returns an integer closest to 'a'
'''
a_ceil = np.ceil(a)
a_floor = np.floor(a)
if np.abs(a_ceil - a) < np.abs(a_floor - a):
return int(a_ceil)
else:
return int(a_floor)
For this purpose I would suggest just do the following thing -
int(round(x))
This will give you nearest integer.
Hope this helps!!
Use round(x, y)
. It will round up your number up to your desired decimal place.
For example:
>>> round(32.268907563, 3)
32.269
I use and may advise the following solution (python3.6):
y = int(x + (x % (1 if x >= 0 else -1)))
It works fine for half-numbers (positives and negatives) and works even faster than int(round(x)):
round_methods = [lambda x: int(round(x)),
lambda x: int(x + (x % (1 if x >= 0 else -1))),
lambda x: np.rint(x).astype(int),
lambda x: int(proper_round(x))]
for rm in round_methods:
%timeit rm(112.5)
Out:
201 ns ± 3.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
159 ns ± 0.646 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
925 ns ± 7.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.18 µs ± 8.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
for rm in round_methods:
print(rm(112.4), rm(112.5), rm(112.6))
print(rm(-12.4), rm(-12.5), rm(-12.6))
print('=' * 11)
Out:
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
For positives, try
int(x + 0.5)
To make it work for negatives too, try
int(x + (0.5 if x > 0 else -0.5))
int()
works like a floor function and hence you can exploit this property. This is definitely the fastest way.