1

Haii friends

How can I convert the string expression value to float value ex: s1 = '100+20*50/10-9' this s1 convert to float value. Based on the arithmetic operator priority rule it should give 191. But the string expression is not convert to float.

I had use float('100+20*50/10-9') and it raises error:

Traceback (most recent call last): File "", line 1, in ValueError: could not convert string to float: '100+20*50/10-9`

Thanks!

Vityata
  • 42,633
  • 8
  • 55
  • 100
  • https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string https://stackoverflow.com/questions/9685946/math-operations-from-string https://stackoverflow.com/questions/43836866/safely-evaluate-simple-string-equation – Josh Lee Apr 16 '18 at 10:58
  • Possible duplicate of [Math operations from string](https://stackoverflow.com/questions/9685946/math-operations-from-string) – Netwave Apr 16 '18 at 10:59

2 Answers2

3

If you are trying to parse a calculation string to a value, you have to evaluate the string first. Like this:

eval('100+20*50/10-9')

Then you may convert it to a float like this float(eval('100+20*50/10-9')).


However, if the calculation string looked like this 101+20*50/3, thus returning 434,3333(3), then you should think of a better solution, parsing the values within to a float before doing the calculation. See the difference:


print float(eval('101+20*50/3'))            '434.0
print float(eval('101.0+20.0*50.0/3.0'))    '434.333333333
Vityata
  • 42,633
  • 8
  • 55
  • 100
0

Also using another method:

s = '101+20*50/3'

print("{:.8f}".format(eval(s)))

#ouput:

434.00000000
Rachit kapadia
  • 705
  • 7
  • 18