¿Cómo redondear un número en Python?


Este problema me está matando. ¿Cómo se redondea un número en Python?

Traté de redondear(número) pero redondear el número hacia abajo. Ejemplo:

round(2.3) = 2.0 and not 3, what I would like

He intentado int(número + .5) pero redondear el número hacia abajo de nuevo! Ejemplo:

int(2.3 + .5) = 2

Luego probé round(número + .5) pero no funcionará en casos extremos. Ejemplo:

WAIT! THIS WORKED!

Por favor avise.

Author: Mr. Me, 2010-03-01

22 answers

La función ceil (techo):

import math
print(math.ceil(4.2))
 597
Author: Steve Tjoa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-26 09:17:18

Interesante Python 2.x problema a tener en cuenta:

>>> import math
>>> math.ceil(4500/1000)
4.0
>>> math.ceil(4500/1000.0)
5.0

El problema es que la división de dos ints en python produce otro int y que se trunca antes de la llamada de techo. Tienes que hacer que un valor sea flotante (o fundido) para obtener un resultado correcto.

En javascript, el mismo código produce un resultado diferente:

console.log(Math.ceil(4500/1000));
5
 134
Author: TrophyGeek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-24 07:33:54

Sé que esta respuesta es para una pregunta de hace un tiempo, pero si no quieres importar matemáticas y solo quieres redondear, esto funciona para mí.

>>> int(21 / 5)
4
>>> int(21 / 5) + (21 % 5 > 0)
5

La primera parte se convierte en 4 y la segunda parte se evalúa como "True" si hay un resto, que además True = 1; False = 0. Así que si no hay resto, entonces permanece el mismo entero, pero si hay un resto añade 1.

 105
Author: user3074620,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-31 14:56:40

Si se trabaja con números enteros, una forma de redondear hacia arriba es aprovechar el hecho de que // redondea hacia abajo: Simplemente haga la división en el número negativo, luego niegue la respuesta. No se necesita importación, coma flotante o condicional.

rounded_up = -(-numerator // denominator)

Por ejemplo:

>>> print(-(-101 // 5))
21
 53
Author: David Bau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-01 08:23:29

También te puede interesar numpy:

>>> import numpy as np
>>> np.ceil(2.3)
3.0

No estoy diciendo que sea mejor que las matemáticas, pero si ya estabas usando numpy para otros propósitos, puedes mantener tu código consistente.

De todos modos, solo un detalle que encontré. Uso mucho numpy y me sorprendió que no se mencionara, pero por supuesto la respuesta aceptada funciona perfectamente bien.

 43
Author: Lisa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-18 13:20:04

Uso math.ceil para redondear:

>>> import math
>>> math.ceil(5.4)
6.0

NOTA: La entrada debe ser flotante.

Si necesita un entero, llame a int para convertirlo:

>>> int(math.ceil(5.4))
6

POR cierto, use math.floorpara redondear hacia abajo y round para redondear al entero más cercano.

>>> math.floor(4.4), math.floor(4.5), math.floor(5.4), math.floor(5.5)
(4.0, 4.0, 5.0, 5.0)
>>> round(4.4), round(4.5), round(5.4), round(5.5)
(4.0, 5.0, 5.0, 6.0)
>>> math.ceil(4.4), math.ceil(4.5), math.ceil(5.4), math.ceil(5.5)
(5.0, 5.0, 6.0, 6.0)
 21
Author: kennytm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-14 11:05:25

La sintaxis puede no ser tan pitónica como a uno le gustaría, pero es una biblioteca poderosa.

Https://docs.python.org/2/library/decimal.html

from decimal import *
print(int(Decimal(2.3).quantize(Decimal('1.'), rounding=ROUND_UP)))
 8
Author: NuclearPeon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-27 19:21:19

Ser shure valor redondeado debe ser flotante

a = 8 
b = 21
print math.ceil(a / b)
>>> 0

Pero

print math.ceil(float(a) / b)
>>> 1.0
 7
Author: Alexey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-30 19:27:18

Me sorprende que nadie sugiera

(numerator + denominator - 1) // denominator

Para la división entera con redondeo hacia arriba. Solía ser la forma común para C / C++ / CUDA (cf. divup)

 6
Author: Andreas Schuh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-08 09:52:00
>>> def roundup(number):
...     return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20

Esta función no requiere módulos.

 6
Author: PonasM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-21 14:16:13

Las respuestas anteriores son correctas, sin embargo, importar el módulo math solo para esta función generalmente se siente como un poco exagerado para mí. Afortunadamente, hay otra manera de hacerlo:

g = 7/5
g = int(g) + (not g.is_integer())

True y False se interpretan como 1 y 0 en una instrucción que involucra números en python. g.is_interger() básicamente se traduce como g.has_no_decimal() o g == int(g). Así que la última declaración en inglés dice round g down and add one if g has decimal.

 4
Author: Nearoo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-05 03:28:44

Sin importar math / / usando envionment básico:

A) método / método de clase

def ceil(fl): 
  return int(fl) + (1 if fl-int(fl) else 0)

def ceil(self, fl): 
  return int(fl) + (1 if fl-int(fl) else 0)

B) lambda:

ceil = lambda fl:int(fl)+(1 if fl-int(fl) else 0)
 4
Author: Kuřátko Zvyk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-19 12:09:29

Prueba esto:

a = 211.0
print(int(a) + ((int(a) - a) != 0))
 4
Author: user3712978,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-05 00:08:09

Me sorprende no haber visto esta respuesta todavía round(x + 0.4999), así que voy a bajarla. Tenga en cuenta que esto funciona con cualquier versión de Python. Los cambios realizados en el esquema de redondeo de Python han dificultado las cosas. Ver este post.

Sin importar, utilizo:

def roundUp(num):
    return round(num + 0.49)

testCases = list(x*0.1 for x in range(0, 50))

print(testCases)
for test in testCases:
    print("{:5.2f}  -> {:5.2f}".format(test, roundUp(test)))

Por qué funciona esto

De los documentos

Para los tipos incorporados que soportan round (), los valores se redondean al múltiplo más cercano de 10 a la potencia menos n; si dos múltiplos son iguales cerca, el redondeo se hace hacia la opción par

Por lo tanto 2.5 se redondea a 2 y 3.5 se redondea a 4. Si este no fuera el caso, entonces el redondeo podría hacerse agregando 0.5, pero queremos evitar llegar al punto medio. Por lo tanto, si agrega 0.4999, se acercará, pero con suficiente margen para redondearlo a lo que normalmente esperaría. Por supuesto, esto fallará si x + 0.4999 es igual a [n].5000, pero eso es poco probable.

 2
Author: Klik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:10

Para aquellos que quieren redondear a / b y obtener entero:

Otra variante que usa la división entera es

def int_ceil(a, b):
    return (a - 1) // b + 1

>>> int_ceil(19, 5)
4
>>> int_ceil(20, 5)
4
>>> int_ceil(21, 5)
5
 1
Author: Pavel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-16 23:52:26

Para hacerlo sin ninguna importación:

>>> round_up = lambda num: int(num + 1) if int(num) != num else int(num)
>>> round_up(2.0)
2
>>> round_up(2.1)
3
 0
Author: gorttar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-15 01:25:26

Sé que esto es de hace bastante tiempo, pero encontré una respuesta bastante interesante, así que aquí va:

-round(-x-0.5)

Esto corrige los casos de bordes y funciona tanto para números positivos como negativos, y no requiere ninguna función import

Salud

 0
Author: Fenmaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-14 08:15:01

Cuando se opera 4500/1000 en python, el resultado será 4, porque por defecto python asume como entero el resultado, lógicamente: 4500/1000 = 4,5 int > int(4,5) = 4 y techo de 4 obviamente es 4

Usando 4500/1000. 0 el resultado será 4.5 y ceil de 4.5 > > 5

Usando javascript recibirá 4.5 como resultado de 4500/1000, porque javascript asume solo el resultado como" tipo numérico " y devuelve un resultado directamente como flotante

¡Buena Suerte!!

 0
Author: erick vicente,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-27 16:46:36

Si no desea importar nada, siempre puede escribir su propia función simple como:

def RoundUP(num): if num== int(num): return num return int(num + 1)

 0
Author: Sebin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-28 17:05:05

Puede usar floor devision y agregarle 1. 2.3 // 2 + 1

 -1
Author: user6612280,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-20 07:07:54

Creo que estás confundiendo los mecanismos de trabajo entre int() y round().

int() siempre trunca los números decimales si se da un número flotante; mientras que round(), en el caso de 2.5 donde 2 y 3 están ambos a la misma distancia de 2.5, Python devuelve lo que esté más lejos del punto 0.

round(2.5) = 3
int(2.5) = 2
 -1
Author: SooBin Kim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-14 19:49:36

Básicamente soy un principiante en Python, pero si solo estás tratando de redondear hacia arriba en lugar de hacia abajo, ¿por qué no hacer:

round(integer) + 1
 -3
Author: Daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-01 02:46:14