1

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

big_moe
  • 11
  • 1
  • 2
    This problem is not well defined. Most multiples of 0.01 cannot be exactly stored as floating-point numbers, although if a number is sufficently close to an exact multiple of 0.01 then python will output only two decimals when converting them to a string. So you will need to define more closely what is meant by having more than two decimals. I would tend to suggest defining some tolerance margin explicitly, rather than just relying on what `str` does with them (which could be implementation-dependent), but that's a choice that you will need to make in defining the problem. – alani Jul 21 '22 at 13:54
  • 1
    If you do `import decimal; a=0.95; print(decimal.Decimal(a))`, you will see a decimal representation of the exact number that is stored internally, and that it is not equal to 0.95, even though if you just do `print(a)` it will output `0.95`. When I try it, I get `0.9499999999999999555910790149937383830547332763671875`, although this may be implementation-dependent, as it depends on the mantissa width (essentially, the number of bits used to store floating point numbers). – alani Jul 21 '22 at 14:07

2 Answers2

0

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])
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75
0

The fraction of the exact float number's value must end with: 0.0, 0.25, 0.5, 0.75.

Algorithm:

  1. Extract the fraction.
  2. Scaled by 4.0.
  3. Test fraction against 0.0.

If non-zero, the original value needs more than 2 places for exact decimal representation.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256