2

How to use Python to handle scientific notation and perform calculations? e.g:

a='1e+03'
b='1e+02'

How to sum a and b and get result of 1.1+03

jpp
  • 159,742
  • 34
  • 281
  • 339
snakehand
  • 39
  • 6

3 Answers3

1

Python's built-in float supports scientific notation:

a = '1e+03'
b = '1e+02'

res = float(a) + float(b)  # 1100.0
print int(res)             # 1100
jpp
  • 159,742
  • 34
  • 281
  • 339
1
c = '{0:0.2e}'.format(float(a)+float(b))

In[10]: c
Out[10]: '1.10e+03'
Osman Mamun
  • 2,864
  • 1
  • 16
  • 22
0

Is usage of float necessary ? I just used as it is and it printed out 1100.0

a = 1e+03

b = 1e+02

print(a+b)

This post might be helpful if you want the result exactly as 1.1+03 . Display a decimal in scientific notation

spnsp
  • 163
  • 1
  • 8
  • It's necessary (or advisable) if your input is a string, as in OP's example. – jpp Dec 21 '18 at 01:37
  • Ah ok. I did not notice the edited question. previous version of the post did not have quotes. – spnsp Dec 21 '18 at 01:44