floating point - Invalid literal in decimal module for python -


well begun infamous floating point weirdness. i'm making simple chess clock , since in chess seconds become important, want update clock every 0.01 second. that's why don't use int variables. tried doing float variables, it's annoying player see 31.2899999999999999 instead of 31.29. googling issue brought me decimal module, looks cool , seems solution, i'm receiving following error:

exception in tkinter callback traceback (most recent call last): file "/library/frameworks/python.framework/versions/3.3/lib/python3.3/tkinter/__init__.py", line 1475, in __call__ return self.func(*args) file "/users/maciek/documents/chessclock/chessclock2.py", line 8, in player1move x=float(player2.get()) file "/library/frameworks/python.framework/versions/3.3/lib/python3.3/tkinter/__init__.py", line 313, in return getint(self._tk.globalgetvar(self._name)) valueerror: invalid literal int() base 10: '29.21' 

i think it's noteworthy first move, when both players have 30 seconds, works well. don't include code player2move function since analogical. aside fixes decimal use, i'm open other idea how make floating values appear (for human eye, is, guess computer 31.2899999999999999 is proper value). here's code:

from decimal import * tkinter import * tkinter import ttk import time  def player1move(*args):     getcontext().prec = 6     x=float(player2.get())     x=decimal(x)     while x>0:         time.sleep(0.01)         x=x-decimal('0.01')         player1.set(decimal(x))         root.update()  root = tk() root.title("python chessclock 2.0")  mainframe = ttk.frame(root, padding="3 3 12 12") mainframe.grid(column=0, row=0, sticky=(n, w, e, s)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1)  player1 = intvar() player1.set(decimal(30)) ttk.label(mainframe, textvariable=player1).grid(column=1, row=1, sticky=(w)) ttk.label(mainframe, textvariable=player2).grid(column=3, row=1, sticky=(e))  root.bind('p', player1move) root.mainloop() 

thanks time!

if read traceback more you'll notice exception has nothing decimal module call getint in tkinter.

also , fwiw don't have use decimal @ if want nice string representation of float - use python's string formating features.


Comments