2

The input I give to a DecimalField of WTFform in Flask application is being converted to a string. I need it be an int or float in order to perform any mathematical operation?

Any help would be appreciated. TIA

  • Possible duplicate of [How do I convert a string to a double in Python?](https://stackoverflow.com/questions/482410/how-do-i-convert-a-string-to-a-double-in-python) – Dekker1 Aug 26 '17 at 13:52

1 Answers1

0

wtforms.DecimalField produces a decimal.Decimal instance.

>>> import wtforms
>>> from webob.multidict import MultiDict
>>> class F(wtforms.Form):
...     foo = wtforms.DecimalField()
... 
>>> f = F(formdata=MultiDict(foo=3.45))
>>> val = f.data['foo']
>>> val
Decimal('3.45000000000000017763568394002504646778106689453125')
>>> type(val)
<class 'decimal.Decimal'>

The object can be used in calculations:

>>> val * 4
Decimal('13.80000000000000071054273576')
>>> val + 2
Decimal('5.450000000000000177635683940')

or can be converted to a float or int using the respective builtin functions

>>> float(val)
3.45
>>> int(val)
3
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153