user3175226
user3175226

Reputation: 3659

python - issues converting string to number (float or integer)

I'm trying to convert string to numbers. It can be float, integer, or empty string.

def num(s):
     if not s: return ""
     try:
          return int(s)
     except ValueError:
          return float(s)
     else: return 0

str1 = ""
str2 = "0.0"
str3 = "1.1"
str4 = "10"

print("str1 = "+str(num(str1)))
print("str2 = "+str(num(str2)))
print("str3 = "+str(num(str3)))
print("str4 = "+str(num(str4)))

so, the output:

str1 =     <== OK
str2 = 0.0 <== I need this as integer 0
str3 = 1.1 <== OK
str4 = 10  <== OK

anyone can help?

Upvotes: 0

Views: 635

Answers (5)

BWStearns
BWStearns

Reputation: 2706

You can check this way. If the float and int of the number are the same then it's an int, else it's a float.

def make_number(n):
    try:
        n = float(n)
        if n == int(n):
            return int(n)
        return float(n)
    except ValueError:
        return 0

Edit: I thought int("1.2") would coerce to 1, I was wrong.

Upvotes: 0

Wei
Wei

Reputation: 375

float(s) can convert string to float directly; and int(float(s)) will convert float to integer. Here we just need a tiny number to check whether the float can be an integer.

def num(s):
    if s == '': 
        return ''
    else:
        if float(s) < int(float(s)) + 0.0000000000001:
            return int(float(s))
        else:
            return float(s)

Upvotes: -1

Raghav RV
Raghav RV

Reputation: 4076

Try this :

Live Running example @ http://codepad.org/9xIbFxJ1

def num(s):

     if not s:
         return ""

     try:

        list_s = s.split(".")

        # If there is no fractional part or fractional part is 0 return int(s) else float(s)

        if ( len(list_s) == 1 ) or ( int(list_s[1]) == 0 ):
            return int(s) 
        else:
            return float(s)

     except: 
        return 0

Upvotes: 1

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

Try this:

def num(s):
    if not s:
        return ""
    try:
        return int(s)
    except ValueError:
        return float(s) or 0
    else:
        return 0

It works as expected:

num('')
=> ''
num('0.0')
=> 0
num('1.1')
=> 1.1
num('10')
=> 10

Upvotes: 1

Andrew Johnson
Andrew Johnson

Reputation: 3186

"0.0"

is not a valid integer string. If you want to round off zeroes into integers then do it after you convert to a float.

def num(s):
    if not s: return ""
    try:
        return int(s)
    except ValueError:
        f = float(s)
        if f%1.0 < 0.0005:
            return int(f)
        else:
            return f
    else: return 0

Upvotes: 2

Related Questions