我需要获取整数和小数的最后 2 位。
我正在使用 number%100
运算符来获取整数的最后 2 位数字。但是,当我尝试对小数进行相同操作时出现错误。
有什么简单的方法可以做到这一点,而无需转换为字符串并进行解析吗?
例子:
number = 1234.56789
我需要得到 89。
56789 % 100 = 89
1234.56789 % 100
给出错误:
ValueError: invalid literal for int() with base 10
更多例子:
number = 0.1
我需要得到 0.1
(带小数点)。
最佳答案
这里是您的问题的有效解决方案:
def last_2_digits_at_best(n):
return float(str(n)[-3:]) if '.' in str(n)[-2:] else int(str(n)[-2:])
print last_2_digits_at_best(1234.56789)
print last_2_digits_at_best(123)
print last_2_digits_at_best(0.1)
print last_2_digits_at_best(1)
print last_2_digits_at_best(0.1 + 0.2)
输出:
89
23
0.1
1
0.3
4.5
1.4
关于python - 如何获取数字的最后 2 位数字(整数或小数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36119213/