简体   繁体   中英

Python: eval() that coerces values to floating point?

Is there a way to execute an eval -like function that coerces its values to floating point? I am hoping to

eval('1/3')

and have it return the floating point value .333333 rather than the integer value 0.

Grab the compiler flag for __future__.division , pass it and your code to compile() , then run eval() on the returned code object.

(note by mh) This has the added advantage of not changing the division operation globally, which might have unexpected side effects. (end note)

>>> import __future__
>>> eval(compile('1/3', '<string>', 'eval', __future__.division.compiler_flag))
0.33333333333333331

You question is really: how can I get Python to do floating point division by default. The answer is:

from __future__ import division

The problem is there is no float value in expression.

try this eval('1/3.0')

This works by default on Python3

Python 3.2 (r32:88445, Dec  8 2011, 15:26:51) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> eval("1/3")
0.3333333333333333

For Python2 you can pass -Qnew on the command line (which is equivalent to from __future__ import division

$ python -Qnew
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> eval("1/3")
0.3333333333333333

Based on Lafada's answer, if you're getting the input string from a variable:

>>> string = '1/3'
>>> print eval(string+'.0')
0.333333333333

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