Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python float to in int conversion

I have an issue that really drives me mad. Normally doing int(20.0) would result in 20. So far so good. But:

levels = [int(gex_dict[i]) for i in sorted(gex_dict.keys())]

while gex_dict[i] returns a float, e.g. 20.0, results in:

"invalid literal for int() with base 10: '20.0'"

I am just one step away from munching the last piece of my keyboard.

like image 426
langohrschnauze Avatar asked Jun 05 '12 13:06

langohrschnauze


People also ask

Can you cast a float to an int?

Since a float is bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that typecasting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value.

How does the int function convert a float to an int?

How does the int function convert a float to an int? By rounding to the nearest whole number. By removing the fractional value of the number.

How do you convert decimal to integer in Python?

Python also has a built-in function to convert floats to integers: int() . In this case, 390.8 will be converted to 390 . When converting floats to integers with the int() function, Python cuts off the decimal and remaining numbers of a float to create an integer.


1 Answers

'20.0' is a string, not a float; you can tell by the single-quotes in the error message. You can get an int out of it by first parsing it with float, then truncating it with int:

>>> int(float('20.0'))
20

(Though maybe you'd want to store floats instead of strings in your dictionary, since that is what you seem to be expecting.)

like image 105
Fred Foo Avatar answered Nov 15 '22 16:11

Fred Foo