How to Parse a String to a Float or Int

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

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

Convert string to either integer or float in javascript

That's how I finally solved it. I didn't find any other solution than to add the variable type to the variable ...

var obj = { a: '2', b: '2.1', c: '2.0', d: 'text'};// Explicitly remember the variable typefor (key in obj) {  var value = obj[key], type;  if ( isNaN(value) || value === "" ) {    type = "string";  }  else {    if (value.indexOf(".") === -1) {      type = "integer";    }    else {      type = "float";    }    value = +value; // Convert string to number  }  obj[key] = {    value: value,    type: type  };}document.write("<pre>" + JSON.stringify(obj, 0, 4) + "</pre>");

Convert String into number (Float or int depending upon the variable entered)

If, for some reason you do not want to use literal_eval, I want to offer another solution using regex. There isn't a necessarily "pretty" built-in method in Python to convert str representations of int and float to int and float respectively.

import re

def conv(n):
if isinstance(n, str) and len(n) > 0:
if re.match(r"^-{0,1}[0-9]+$", n):
return int(n)
elif re.match(r"^-{0,1}[0-9]+(\.|e)[0-9]+$", n):
return float(n)
return n
>>> conv("-123")
-123
>>> conv("123.4")
123.4
>>> conv("2e2")
200.0

PYTHON How to convert string into int or float

It is better to add if statement. For example

if int(res) == res:
res = int(res)

How can I convert a string to either int or float with priority on int?

def int_or_float(s):
try:
return int(s)
except ValueError:
return float(s)

If you want something like "10.0000" converted to int, try this:

def int_dammit_else_float(s):
f = float(s)
i = int(f)
return i if i == f else f

What result do you want for input like "1e25"?

Convert a List of string to Int or Float as available

You could make use of float.is_integer():

>>> lst = ['67.50', '70.00', '72.50', '75.00', '77.50', '80.00', '82.50']
>>> [int(x) if x.is_integer() else x for x in map(float, lst)]
[67.5, 70, 72.5, 75, 77.5, 80, 82.5]

How to convert String into Float?

Your line should be pi_float = float(pi_string)

float(pi_string) is a float value, you can not assign to it, because it is not a variable.



Related Topics



Leave a reply



Submit