Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a string to a float or int?

In Python, how can I parse a numeric string like

"545.2222"  

to its corresponding float value,

545.2222 

? Or parse the string "31" to an integer, 31?

I just want to know how to parse a float str to a float, and (separately) an int str to an int.

like image 773
Tristan Havelick Avatar asked Dec 19 '08 01:12

Tristan Havelick


People also ask

How do you convert a string to an int or a float?

In Python, you can convert a string str to an integer int and a floating point number float with int() and float() . This article describes the following contents. Use str() to convert an integer or floating point number to a string. You can also convert a list of strings to a list of numbers.

How do you convert a string to a float?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

How do I turn a string into an int?

Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.


1 Answers

>>> a = "545.2222" >>> float(a) 545.22220000000004 >>> int(float(a)) 545 
like image 190
Harley Holcombe Avatar answered Sep 20 '22 12:09

Harley Holcombe