convert user input to Decimal objects using eval()?
Terry Reedy
tjreedy at udel.edu
Tue Mar 29 20:58:36 EST 2005
"Raymond Hettinger" <vze4rx4y at verizon.net> wrote in message
news:6_72e.50077$u76.2569 at trndny08...
> [Julian Hernandez Gomez]
>> This is maybe a silly question, but...
>>
>> is there a "easy way" to make eval() convert all floating
>> numbers to Decimal objects and return a Decimal?
>
> from decimal import Decimal
> import re
>
> number =
> re.compile(r"((\b|(?=\W))(\d+(\.\d*)?|\.\d+)([eE][+-]?\d{1,3})?)")
> deciexpr = lambda s: number.sub(r"Decimal('\1')", s)
>
> for s in ('1.00000001+0.1111111',
> '+21.3e-5*85-.1234/81.6',
> '1.0/7'):
> print '%s\n --> %r' % (s, eval(s))
> s = deciexpr(s)
> print '%s\n --> %r\n' % (s, eval(s))
>
>
>
> """
> 1.00000001+0.1111111
> --> 1.11111111
> Decimal('1.00000001')+Decimal('0.1111111')
> --> Decimal("1.11111111")
>
> +21.3e-5*85-.1234/81.6
> --> 0.016592745098039215
> +Decimal('21.3e-5')*Decimal('85')-Decimal('.1234')/Decimal('81.6')
> --> Decimal("0.01659274509803921568627450980")
>
> 1.0/7
> --> 0.14285714285714285
> Decimal('1.0')/Decimal('7')
> --> Decimal("0.1428571428571428571428571429")
This is less obvious and more useful, to me, than some of the recipies in
the new Cookbook.
TJR
More information about the Python-list
mailing list