你如何在Python中找到一个数字?

时间:2022-12-08 23:21:20

This problem is killing me. How does one roundup a number UP in Python?

这个问题快把我逼疯了。如何在Python中使用一个数字?

I tried round(number) but it round the number down. Example:

我试了一下(数字),但数字是整数。例子:

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

The I tried int(number + .5) but it round the number down again! Example:

我试了一下(数字+ .5),但又把数字又打了一圈!例子:

int(2.3 + .5) = 2

Then I tried round(number + .5) but it won't work in edge cases. Example:

然后我试了一下(数字+ .5),但在边界情况下是行不通的。例子:

WAIT! THIS WORKED!

Please advise.

请建议。

21 个解决方案

#1


512  

The ceil (ceiling) function:

装天花板(天花板)功能:

import math
print(math.ceil(4.2))

#2


124  

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. You have to make one value a float (or cast) to get a correct result.

问题是,在python中划分两个ints产生另一个int,并且在上限调用之前被截断。为了得到正确的结果,您必须使一个值变为浮点数(或cast)。

In javascript, the exact same code produces a different result:

在javascript中,完全相同的代码产生了不同的结果:

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

#3


89  

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; False = 0. So if there is no remainder, then it stays the same integer, but if there is a remainder it adds 1.

第一部分为4,第二部分为“True”,如果有余数,则为True = 1;假= 0。所以如果没有余数,那么它就保持相同的整数,但如果有余数,它加1。

#4


36  

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,我很惊讶它没有被提到,但是当然这个公认的答案很好。

#5


34  

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

#6


19  

Use math.ceil to round up:

使用数学。装天花板围捕:

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

#7


6  

The syntax may not be as pythonic as one might like, but it is a powerful library.

它的语法可能不像一个人所喜欢的python,但它是一个强大的库。

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

#8


5  

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

#9


4  

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 (cf. divup)的常用方法

#10


2  

I'm surprised I haven't seen this answer yet round(x + 0.4999), so I'm going to put it down. Note that this works with any Python version. Changes made to the Python rounding scheme has made things difficult. See this post.

我很惊讶我还没有看到这个答案(x + 0.4999),所以我要把它写下来。请注意,这适用于任何Python版本。对Python舍入方案的更改使事情变得困难。看到这篇文章。

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; if two multiples are equally close, rounding is done toward the even choice

对于内置类型支持round(),将值四舍五入到最接近10的倍数到幂减n;如果两个倍数是相等的,那么舍入是对偶数的选择。

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. So, if you add 0.4999 you will get close, but with enough margin to be rounded to what you would normally expect. Of course, this will fail if the x + 0.4999 is equal to [n].5000, but that is unlikely.

因此,2。5被四舍五入到2,3。5得到四舍五入。如果不是这样的话,可以通过加0。5来进行舍入,但我们要避免到达中点。所以,如果你加0。4999,你就会接近,但有足够的余量,你会得到你通常期望的。当然,如果x + 0.4999等于[n],这将会失败。但这是不可能的。

#11


2  

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. 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. g.is_interger() basically translates to g.has_no_decimal() or g == int(g). So the last statement in English reads round g down and add one if g has decimal.

在包含python数字的语句中,True和False被解释为1和0。is_interger()基本上翻译为g.has_no_decimal()或g == int(g)。所以最后一个用英语写的语句是把g写下来,如果g有小数,就加1。

#12


2  

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)

#13


1  

Try this:

试试这个:

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

#14


0  

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, asume是整型的结果,逻辑上是:4500/1000 = 4.5—> int(4.5) = 4,而ceil 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只将结果作为“数字类型”,并直接返回结果为float。

Good Luck!!

祝你好运! !

#15


0  

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

#16


-1  

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

#17


-1  

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

干杯

#18


-1  

You can use floor devision and add 1 to it. 2.3 // 2 + 1

你可以使用地板去视觉,然后加1。2.3 // 2 + 1。

#19


-1  

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)

def RoundUP(num):如果num== int(num):返回num返回int(num + 1)

#20


-2  

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; 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.

在给定浮点数时,int()总是截断十进制数;而round(),在2.5的情况下,2和3的距离都小于2.5,而Python返回的则是大于0的值。

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

#21


-4  

I'm basically a beginner at Python, but if you're just trying to round up instead of down why not do:

我基本上是Python的初学者,但如果你只是试着去做,而不是向下,为什么不做:

round(integer) + 1

#1


512  

The ceil (ceiling) function:

装天花板(天花板)功能:

import math
print(math.ceil(4.2))

#2


124  

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. You have to make one value a float (or cast) to get a correct result.

问题是,在python中划分两个ints产生另一个int,并且在上限调用之前被截断。为了得到正确的结果,您必须使一个值变为浮点数(或cast)。

In javascript, the exact same code produces a different result:

在javascript中,完全相同的代码产生了不同的结果:

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

#3


89  

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; False = 0. So if there is no remainder, then it stays the same integer, but if there is a remainder it adds 1.

第一部分为4,第二部分为“True”,如果有余数,则为True = 1;假= 0。所以如果没有余数,那么它就保持相同的整数,但如果有余数,它加1。

#4


36  

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,我很惊讶它没有被提到,但是当然这个公认的答案很好。

#5


34  

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

#6


19  

Use math.ceil to round up:

使用数学。装天花板围捕:

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

#7


6  

The syntax may not be as pythonic as one might like, but it is a powerful library.

它的语法可能不像一个人所喜欢的python,但它是一个强大的库。

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

#8


5  

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

#9


4  

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 (cf. divup)的常用方法

#10


2  

I'm surprised I haven't seen this answer yet round(x + 0.4999), so I'm going to put it down. Note that this works with any Python version. Changes made to the Python rounding scheme has made things difficult. See this post.

我很惊讶我还没有看到这个答案(x + 0.4999),所以我要把它写下来。请注意,这适用于任何Python版本。对Python舍入方案的更改使事情变得困难。看到这篇文章。

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; if two multiples are equally close, rounding is done toward the even choice

对于内置类型支持round(),将值四舍五入到最接近10的倍数到幂减n;如果两个倍数是相等的,那么舍入是对偶数的选择。

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. So, if you add 0.4999 you will get close, but with enough margin to be rounded to what you would normally expect. Of course, this will fail if the x + 0.4999 is equal to [n].5000, but that is unlikely.

因此,2。5被四舍五入到2,3。5得到四舍五入。如果不是这样的话,可以通过加0。5来进行舍入,但我们要避免到达中点。所以,如果你加0。4999,你就会接近,但有足够的余量,你会得到你通常期望的。当然,如果x + 0.4999等于[n],这将会失败。但这是不可能的。

#11


2  

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. 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. g.is_interger() basically translates to g.has_no_decimal() or g == int(g). So the last statement in English reads round g down and add one if g has decimal.

在包含python数字的语句中,True和False被解释为1和0。is_interger()基本上翻译为g.has_no_decimal()或g == int(g)。所以最后一个用英语写的语句是把g写下来,如果g有小数,就加1。

#12


2  

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)

#13


1  

Try this:

试试这个:

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

#14


0  

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, asume是整型的结果,逻辑上是:4500/1000 = 4.5—> int(4.5) = 4,而ceil 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只将结果作为“数字类型”,并直接返回结果为float。

Good Luck!!

祝你好运! !

#15


0  

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

#16


-1  

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

#17


-1  

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

干杯

#18


-1  

You can use floor devision and add 1 to it. 2.3 // 2 + 1

你可以使用地板去视觉,然后加1。2.3 // 2 + 1。

#19


-1  

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)

def RoundUP(num):如果num== int(num):返回num返回int(num + 1)

#20


-2  

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; 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.

在给定浮点数时,int()总是截断十进制数;而round(),在2.5的情况下,2和3的距离都小于2.5,而Python返回的则是大于0的值。

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

#21


-4  

I'm basically a beginner at Python, but if you're just trying to round up instead of down why not do:

我基本上是Python的初学者,但如果你只是试着去做,而不是向下,为什么不做:

round(integer) + 1