问题
I'm trying to test if a float
i.e(54.10
) is divisible by 0.10
. 54.10 % .10
returns .10
and not 0
, why is that and how can I get it to do what I want it to do?
回答1:
You can use the decimal module to avoid the floating point precision problem:
>>> import decimal
>>> decimal.Decimal('54.10') % decimal.Decimal('0.10')
Decimal('0.00')
回答2:
The tried and true method here is to multiply your divisor and dividend by a power of 10. Effectively, 54.10 becomes 541 and 0.10 becomes 1. Then you can use standard modulo or ceiling and floor to achieve what you need.
来源:https://stackoverflow.com/questions/32064356/how-to-test-if-a-number-is-divisible-by-a-decimal-less-than-1-54-10-10