how to test if a number is divisible by a decimal less than 1? (54.10 % .10)

匆匆过客 提交于 2020-02-25 17:00:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!