0

When executing a expression with eval(), the output for some input is wrong. I think the decimal values are not considered.

I have been trying to evaluate a string with python eval() and also tried numexpr()

def _calc_line_base_amount(text):
        num = '0123456789*-+/()'
        # here text = "3/2*5"
        if text:
            for char in text:
                if char not in num:
                    text = text.replace(char, "")
        return eval(str(text))

and also tried this one too

import numexpr as ne
print(ne.evaluate("3/2*5"))

Input 3/2*5 Expected output 7.5 Actual Output is 5

Edit:: In python3+ It works. But I am running this python2.7

CZoellner
  • 13,553
  • 3
  • 25
  • 38
SREEJITH
  • 78
  • 14
  • 3
    If you are using Python 2.x, 3/2 will give you 1. You need to use 3.0/2 or 3/2.0. (make one(or both) of the int, float. – Lafexlos Oct 18 '19 at 08:04
  • 1
    i ran your code, it seems fine, i got 7.5 in both – Jingles Oct 18 '19 at 08:05
  • 1
    Possible duplicate of [What is the difference between '/' and '//' when used for division?](https://stackoverflow.com/questions/183853/what-is-the-difference-between-and-when-used-for-division) – Lafexlos Oct 18 '19 at 08:09

1 Answers1

0

Both are working fine and giving the same output

using function eval() 7.5

using numexpr numexpr 7.5

Make sure you have installed nuexpr for the 2nd one, and make sure you are using python3.