I need a solution to access all numbers that have more than two decimals. e.g.
Have:
nums = [0.95, 0.7, 0.0, 0.3234, 0.54563]
Need:
many_decimals = [0.3234, 0.54563]
Thanks a lot :)
I need a solution to access all numbers that have more than two decimals. e.g.
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
If the number is a whole integer (e.g. 100) then s.find('.') returns -1 so this still works for the case of checking more than 2 decimal places.
An alternative posted in a related question uses the decimal package and the exponent property. Using this approach creates the same output as above.
import decimal
print([f for f in nums if abs(decimal.Decimal(str(f)).as_tuple().exponent) > 2])
The fraction of the exact float number's value must end with: 0.0, 0.25, 0.5, 0.75
.
Algorithm:
If non-zero, the original value needs more than 2 places for exact decimal representation.