简体   繁体   English

你如何四舍五入一个数字?

[英]How do you round UP a number?

How does one round a number UP in Python?如何在 Python 中将一个数字向上取整?

I tried round(number) but it rounds the number down.我尝试round(number)但它向下舍入了数字。 Example:例子:

round(2.3) = 2.0 

and not 3, as I would like.而不是 3,如我所愿。

The I tried int(number + .5) but it round the number down again!我试过int(number + .5)但它又把数字四舍五入了! Example:例子:

int(2.3 + .5) = 2

The math.ceil (ceiling) function returns the smallest integer higher or equal to x . math.ceil (ceiling) 函数返回大于或等于x的最小整数。

For Python 3:对于 Python 3:

import math
print(math.ceil(4.2))

For Python 2:对于 Python 2:

import math
print(int(math.ceil(4.2)))

I know this answer is for a question from a while back, but if you don't want to import math and you just want to round up, this works for me.我知道这个答案是针对不久前的一个问题,但是如果您不想导入数学并且只想四舍五入,这对我有用。

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

The first part becomes 4 and the second part evaluates to "True" if there is a remainder, which in addition True = 1;第一部分变为 4,如果有余数,则第二部分计算为“True”,此外 True = 1; False = 0. So if there is no remainder, then it stays the same integer, but if there is a remainder it adds 1. False = 0。因此,如果没有余数,则保持相同的整数,但如果有余数,则加 1。

Interesting Python 2.x issue to keep in mind:要记住的有趣的 Python 2.x 问题:

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

The problem is that dividing two ints in python produces another int and that's truncated before the ceiling call.问题是在 python 中划分两个 int 会产生另一个 int 并且在上限调用之前被截断。 You have to make one value a float (or cast) to get a correct result.您必须将一个值设为浮点数(或强制转换)才能获得正确的结果。

In javascript, the exact same code produces a different result:在 javascript 中,完全相同的代码会产生不同的结果:

console.log(Math.ceil(4500/1000));
5

If working with integers, one way of rounding up is to take advantage of the fact that // rounds down: Just do the division on the negative number, then negate the answer.如果使用整数,向上舍入的一种方法是利用//向下舍入的事实:只需对负数进行除法,然后否定答案。 No import, floating point, or conditional needed.不需要导入、浮点或条件。

rounded_up = -(-numerator // denominator)

For example:例如:

>>> print(-(-101 // 5))
21

You might also like numpy:你可能还喜欢 numpy:

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

I'm not saying it's better than math, but if you were already using numpy for other purposes, you can keep your code consistent.我并不是说它比数学好,但如果你已经将 numpy 用于其他目的,你可以保持你的代码一致。

Anyway, just a detail I came across.无论如何,只是我遇到的一个细节。 I use numpy a lot and was surprised it didn't get mentioned, but of course the accepted answer works perfectly fine.我经常使用 numpy 并且很惊讶它没有被提及,但当然接受的答案非常好。

Use math.ceil to round up:使用math.ceil进行四舍五入:

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

NOTE : The input should be float.注意:输入应该是浮动的。

If you need an integer, call int to convert it:如果需要整数,请调用int进行转换:

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

BTW, use math.floor to round down and round to round to nearest integer.顺便说一句,使用math.floor向下舍入并round到最接近的整数。

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

I am surprised nobody suggested我很惊讶没有人建议

(numerator + denominator - 1) // denominator

for integer division with rounding up.用于四舍五入的整数除法。 Used to be the common way for C/C++/CUDA (cf. divup )曾经是 C/C++/CUDA 的常用方式(参见divup

The syntax may not be as pythonic as one might like, but it is a powerful library.语法可能不像人们喜欢的那样 Pythonic,但它是一个强大的库。

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

from decimal import *
print(int(Decimal(2.3).quantize(Decimal('1.'), rounding=ROUND_UP)))

For those who want to round up a / b and get integer:对于那些想要四舍五入a / b并获得整数的人:

Another variant using integer division is使用整数除法的另一个变体是

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

Note: a and b must be non-negative integers注意: ab必须是非负整数

Try this:尝试这个:

a = 211.0
print(int(a) + ((int(a) - a) != 0))

Be shure rounded value should be float舒尔四舍五入的值应该是浮点数

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

but

print math.ceil(float(a) / b)
>>> 1.0

The above answers are correct, however, importing the math module just for this one function usually feels like a bit of an overkill for me.上面的答案是正确的,但是,只为这个函数导入math模块对我来说通常感觉有点矫枉过正。 Luckily, there is another way to do it:幸运的是,还有另一种方法:

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

True and False are interpreted as 1 and 0 in a statement involving numbers in python.在 python 中涉及数字的语句中, TrueFalse被解释为10 g.is_interger() basically translates to g.has_no_decimal() or g == int(g) . g.is_interger()基本上转换为g.has_no_decimal()g == int(g) So the last statement in English reads round g down and add one if g has decimal .因此,英语的最后一条语句将round g down and add one if g has decimal

Without importing math // using basic envionment:无需导入数学 // 使用基本环境:

a) method / class method a) 方法/类方法

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: b) 拉姆达:

ceil = lambda fl:int(fl)+(1 if fl-int(fl) else 0)
>>> def roundup(number):
...     return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20

This function requires no modules.此功能不需要模块。

In case anyone is looking to round up to a specific decimal place:如果有人希望四舍五入到特定的小数位:

import math
def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier

x * -1 // 1 * -1

Confusing but it works: For x=7.1 , you get 8.0 .令人困惑但它有效:对于x=7.1 ,你得到8.0 For x = -1.1 , you get -1.0对于x = -1.1 ,你得到-1.0

No need to import a module.无需导入模块。

Here is a way using modulo and bool这是一种使用modulobool的方法

n = 2.3
int(n) + bool(n%1)

Output:输出:

3

For those who doesn't want to use import.对于那些不想使用导入的人。

For a given list or any number:对于给定的列表或任何数字:

x = [2, 2.1, 2.5, 3, 3.1, 3.5, 2.499,2.4999999999, 3.4999999,3.99999999999]

You must first evaluate if the number is equal to its integer, which always rounds down.您必须首先评估该数字是否等于其整数,该整数始终向下舍入。 If the result is True, you return the number, if is not, return the integer(number) + 1.如果结果为真,则返回数字,如果不是,则返回整数(数字)+ 1。

w = lambda x: x if x == int(x) else int(x)+1
[w(i) for i in z]
>>> [2, 3, 3, 3, 4, 4, 3, 3, 4, 4]

Math logic:数学逻辑:

  • If the number has decimal part: round_up - round_down == 1, always.如果数字有小数部分:round_up - round_down == 1,总是。
  • If the number doens't have decimal part: round_up - round_down == 0.如果数字没有小数部分:round_up - round_down == 0。

So:所以:

  • round_up == x + round_down round_up == x + round_down

With:和:

  • x == 1 if number != round_down x == 1 如果数字 != round_down
  • x == 0 if number == round_down x == 0 如果数字 == round_down

You are cutting the number in 2 parts, the integer and decimal.您将数字分成两部分,整数和小数。 If decimal isn't 0, you add 1.如果小数不为 0,则加 1。

PS:I explained this in details since some comments above asked for that and I'm still noob here, so I can't comment. PS:我对此进行了详细解释,因为上面的一些评论要求这样做,而我在这里仍然是菜鸟,所以我无法发表评论。

你可以像这样使用圆形:

cost_per_person = round(150 / 2, 2)

  

To do it without any import:要在没有任何导入的情况下执行此操作:

>>> round_up = lambda num: int(num + 1) if int(num) != num else int(num)
>>> round_up(2.0)
2
>>> round_up(2.1)
3

I know this is from quite a while back, but I found a quite interesting answer, so here goes:我知道这是很久以前的事了,但我找到了一个非常有趣的答案,所以这里是:

-round(-x-0.5)

This fixes the edges cases and works for both positive and negative numbers, and doesn't require any function import这修复了边缘情况并适用于正数和负数,并且不需要任何函数导入

Cheers干杯

I'm surprised I haven't seen this answer yet round(x + 0.4999) , so I'm going to put it down.我很惊讶我还没有看到这个答案round(x + 0.4999) ,所以我要把它记下来。 Note that this works with any Python version.请注意,这适用于任何 Python 版本。 Changes made to the Python rounding scheme has made things difficult.对 Python 舍入方案所做的更改使事情变得困难。 See this post .看到这个帖子

Without importing, I use:不导入,我使用:

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

Why this works为什么这有效

From the docs从文档

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus n;对于支持 round() 的内置类型,值被四舍五入到最接近的 10 的负 n 次方倍数; if two multiples are equally close, rounding is done toward the even choice如果两个倍数同样接近,则朝偶数选择舍入

Therefore 2.5 gets rounded to 2 and 3.5 gets rounded to 4. If this was not the case then rounding up could be done by adding 0.5, but we want to avoid getting to the halfway point.因此,2.5 舍入为 2,3.5 舍入为 4。如果不是这种情况,则可以通过添加 0.5 进行舍入,但我们希望避免到达中间点。 So, if you add 0.4999 you will get close, but with enough margin to be rounded to what you would normally expect.因此,如果您添加 0.4999,您将接近,但有足够的余量可以四舍五入到您通常期望的值。 Of course, this will fail if the x + 0.4999 is equal to [n].5000 , but that is unlikely.当然,如果x + 0.4999等于[n].5000 ,这将失败,但这不太可能。

If you don't want to import anything, you can always write your own simple function as:如果您不想导入任何内容,您可以随时编写自己的简单函数:

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

You can use floor devision and add 1 to it.您可以使用楼层划分并为其添加 1。 2.3 // 2 + 1 2.3 // 2 + 1

when you operate 4500/1000 in python, result will be 4, because for default python asume as integer the result, logically: 4500/1000 = 4.5 --> int(4.5) = 4 and ceil of 4 obviouslly is 4当您在 python 中操作 4500/1000 时,结果将为 4,因为对于默认 python 假定结果为整数,逻辑上:4500/1000 = 4.5 --> int(4.5) = 4 并且 ceil of 4 显然是 4

using 4500/1000.0 the result will be 4.5 and ceil of 4.5 --> 5使用 4500/1000.0 结果将是 4.5 和 ceil 为 4.5 --> 5

Using javascript you will recieve 4.5 as result of 4500/1000, because javascript asume only the result as "numeric type" and return a result directly as float使用 javascript,您将收到 4.5 作为 4500/1000 的结果,因为 javascript 仅假定结果为“数字类型”并直接将结果作为浮点数返回

Good Luck!!祝你好运!!

https://docs.python.org/2/library/math.html look for math.ceil https://docs.python.org/2/library/math.html寻找math.ceil

"Return the ceiling of x as a float, the smallest integer value greater than or equal to x." “将x的上限作为浮点数返回,最大整数值大于或等于x。”

I think you are confusing the working mechanisms between int() and round() .我认为您混淆了int()round()之间的工作机制。

int() always truncates the decimal numbers if a floating number is given;如果给出浮点数, int()总是截断十进制数; whereas round() , in case of 2.5 where 2 and 3 are both within equal distance from 2.5 , Python returns whichever that is more away from the 0 point.round() ,在2.5的情况下,其中23都在与2.5相等的距离内,Python 返回距离 0 点更远的那个。

round(2.5) = 3
int(2.5) = 2

My share我的份额

I have tested print(-(-101 // 5)) = 21 given example above.我已经测试了print(-(-101 // 5)) = 21上面给出的例子。

Now for rounding up:现在进行四舍五入:

101 * 19% = 19.19

I can not use ** so I spread the multiply to division:我不能使用**所以我将乘法扩展到除法:

(-(-101 //(1/0.19))) = 20

我基本上是 Python 的初学者,但如果你只是想向上取整而不是向下取整,为什么不这样做:

round(integer) + 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM