简体   繁体   中英

Check if a number is divisible by another in python

I would like to check the following

This settings work

number = 100
divisor = 10

These do not

number = 100
divisor = 0.1

Scenario 1 shows correct answer however Scenario 2 does not. What would be the best way to have this show correct result.

def isDivisible(number, divisor):
    return (number % divisor)

number = 100
divisor = 10

print("Scenario 1:")
print("")
print("Number = " + str(number))
print("Divisor = " + str(divisor))
print("")
print("Answer:")
if isDivisible(number, divisor) == 0:
    print("Answer: True")
    print("Value: " + str(isDivisible(number, divisor)))
else:
    print("Answer: False")
    print("Value: " + str(isDivisible(number, divisor)))

print("")
print("##################")
print("")

number = 100
divisor = 0.1

print("Scenario 2:")
print("")
print("Number = " + str(number))
print("Divisor = " + str(divisor))
print("")
print("Answer:")
if isDivisible(number, divisor) == 0:
    print("Answer: True")
    print("Value: " + str(isDivisible(number, divisor)))
else:
    print("Answer: False")
    print("Value: " + str(isDivisible(number, divisor)))

print("")

Based on your examples, you're using floating point numbers. Floating point numbers have a lot of limitations--most importantly, they are limited in their precision. To be frank, I'm surprised floating point modulus even works. It should probably be a TypeError .

Try using the decimal package from the Python standard library and see if you have more success.

Not sure if this is correct answer but seems to work fine. I converted to decimal using number as a string. I tried just using decimal without converting to string however i got a lot of junk on the end of "number" variable so it didn't work out.

from decimal import Decimal # Added this

def isDivisible(number, divisor):
    return (number % divisor)

number = 10
divisor = 0.0001
divisor = Decimal(str(divisor))
number = Decimal(str(number))

print("Number = " + str(number)) # Added this
print("Divisor = " + str(divisor)) # Added this
print("")
if isDivisible(number, divisor) == 0:
    print("Answer: True")
    print("Value: " + str(isDivisible(number, divisor)))
else:
    print("Answer: False")
    print("Value: " + str(isDivisible(number, divisor)))

print("")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM