[英]How can I find float numbers that have more than two decimals? (Python)
I need a solution to access all numbers that have more than two decimals.我需要一个解决方案来访问所有小数点后两位以上的数字。 eg例如
Have:有:
nums = [0.95, 0.7, 0.0, 0.3234, 0.54563]
Need:需要:
many_decimals = [0.3234, 0.54563]
Thanks a lot:)非常感谢:)
You can convert to string, reverse the string, then get index of '.'您可以转换为字符串,反转字符串,然后获取 '.' 的索引in the string which is the count of decimal places.在字符串中,它是小数位数。
Try something like this:尝试这样的事情:
nums = [0.95, 0.7, 0.0, 0.3234, 0.54563]
print([f for f in nums if str(f)[::-1].find('.') > 2])
Output:输出:
[0.3234, 0.54563]
Solution breakdown:解决方案分解:
s = str(0.54563)[::-1] # => '36545.0'
s.find('.') # => 5
An alternative can use the decimal package and use the exponent, which creates the same output as above.另一种方法可以使用 decimal 包并使用 exponent,它创建与上述相同的输出。
import decimal
print([f for f in nums if abs(decimal.Decimal(str(f)).as_tuple().exponent) > 2])
10**x*n%1>0
will return True if n has more than x decimals 10**x*n%1>0
如果 n 有超过 x 个小数,将返回 True
so you can do many_decimals = [n for n in nums if 10**2*n%1>0]
所以你可以做many_decimals = [n for n in nums if 10**2*n%1>0]
10**x*n%1>0
is ((10**x) * n) % 1 > 0
: 10**x*n%1>0
是((10**x) * n) % 1 > 0
:
The fraction of the exact float number's value must end with: 0.0, 0.25, 0.5, 0.75
.精确浮点数的小数部分必须以: 0.0, 0.25, 0.5, 0.75
结尾。
Algorithm:算法:
If non-zero, the original value needs more than 2 places for exact decimal representation.如果非零,则原始值需要多于 2 位才能精确表示十进制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.