简体   繁体   English

根据位数将 integer 向上舍入到下一个 99

[英]Round up integer to the next 99 depending on the number of digits

How do I use math.ceil() to round up a number to the maximum of it's base.如何使用 math.ceil() 将数字四舍五入到其基数的最大值。 For example, if the number is between例如,如果数字介于

0 - 9 -> 9
10 - 99 -> 99
100 - 999 -> 999
1000 - 9999 -> 9999

so forth.等等。 I've done it by counting the number of digits but I'm looking for a pythonic way我已经通过计算位数来完成它,但我正在寻找一种 Pythonic 方式

Here is one way to do this using the ceiling along with logarithms:这是使用上限和对数的一种方法:

def round_by_tens(inp):
    z = math.ceil(math.log10(inp+1))
    q = (10 ** z) - 1
    return q

nums = [5, 50, 500, 5000]
for num in nums:
    print(round_by_tens(num))

This prints:这打印:

9.0
99.0
999.0
9999.0

The logic here is to first compute the ceiling power of 10 which would be required to generate the tens factor which is the upper bound of the input.这里的逻辑是首先计算 10 的上限功率,这将需要生成作为输入上限的 10 因子。 Then, we simply take that tens upper bound, and subtract one from it to generate the output you expect.然后,我们简单地取这 10 个上限,并从中减去 1 以生成您期望的 output。

You can use the following also:您还可以使用以下内容:

def repeat_to_length(string_to_expand, length):
    return int(string_to_expand * length)


num = 0
print(repeat_to_length("9", len(str(num))))
# 9
num = 45
print(repeat_to_length("9", len(str(num))))
# 99
num = 123
print(repeat_to_length("9", len(str(num))))
# 999

I would probably use this:我可能会使用这个:

def round9(x):
    r = 10
    while x >= 10: 
        r *= 10
        x //= 10
    return r-1

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

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