Converting a number in scientific notation to int

Can someone explain why I cannot use int() to convert an integer represented in a string-scientific notation to python int ?

For example, this does not work:

 print int('1e1') 

But it does:

 print int(float('1e1')) print int(1e1) # Works 

Why does int not recognize the string as an integer? Sure, it's as simple as checking the exponent?

+6
source share
2 answers

Behind the scenes, the notation of scientific numbers is always presented as a float inside. The reason is that the range of changing numbers, since an integer is only displayed in a fixed range of values, say 2^32 . A scientific presentation is like a floating presentation with a significant and exponential. You can find more information at https://en.wikipedia.org/wiki/Floating_point .

You cannot pass a scientific numeric representation as a string to an integer.

 print int(1e1) # Works 

It works because 1e1 as a number is already a float.

 >>> type(1e1) <type 'float'> 

Back to your question: We want to get an integer from a float or scientific string. Details: https://docs.python.org/2/reference/lexical_analysis.html#integers

 >>> int("13.37") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '13.37' 

For floating or scientific presentations, you need to use an intermediate step over the float .

+2
source

Because in Python (at least in 2.x, since I do not use Python 3.x), int() behaves differently in strings and numerical values. If you enter a string, then python will try to parse it based on 10 int

 int ("077") >> 77 

But if you enter a valid numeric value, then python will interpret it according to its base and type and convert it to base 10 int.

 int (077) # Leading 0 defines a base 8 number. >> 63 

So int('1e1') will try to 1e1 as the base string of 10 and throw a ValueError . But 1e1 is a numerical value (mathematical expression):

 1e1 >> 10.0 

So, int will process it as a numeric value and process it as if converting it to float(10.0) , and then parse it into int.

Thus, by calling int() with a string value, you must be sure that the string is a valid integer value.

+1
source

All Articles