My code does not run as I would expect if one float variable has 5 digits, others have 4, and an arithmetical operation is performed on them. For example:
def capacity(self):
mmax = self.mmax.get()
current = self.current.get()
mmin = self.mmin.get()
flag = False
if flag is False:
if mmax.isdigit() and mmin.isdigit() and current.isdigit():
capacity = float(100 * ((float(current) - float(mmin)) / (float(mmax) - float(mmin))))
if mmin <= current <= mmax and 0 <= capacity <= 100:
flag = True
else:
self.result = str("Please ensure the values entered correspond to the correct value.")
else:
self.result = str("Please enter only positive integers.")
if flag is True:
self.result = "Capacity: %2.2f" % capacity + '%'
If mmax = 10000, current = 5000, and mmin = 1000
, self.result = str("Please ensure...")
.
If mmax = 9999, current = 5000, and mmin = 1000
, self.result = str("Capacity: 44.45%)
.
What's going on here/ how can I overcome this problem?
I'm guessing that mmin
and current
and mmax
are strings. In which case, this expression:
if mmin <= current <= mmax and 0 <= capacity <= 100:
... Is doing a lexicographical comparison on the values. This is different from a numerical comparison: for example, "5000" < "10000"
evaluates to False because "5" is larger than "1".
Convert your values to numbers before doing comparisons on them.
if mmax.isdigit() and mmin.isdigit() and current.isdigit():
mmax = float(mmax)
current = float(current)
mmin = float(mmin)
capacity = float(100 * ... #etc
Or
if float(mmin) <= float(current) <= float(mmax) and 0 <= capacity <= 100: