0

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?

8
  • 1
    Why do you want the string representation of a float to become an integer?! Commented Jul 24, 2014 at 23:31
  • 1
    Yes, you are converting, that is clear. My question is: why should '0.0' be converted to 0, not 0.0, when it clearly represents the latter? Commented Jul 24, 2014 at 23:34
  • 1
    @user3175226 that still does not explain why you want to convert a float to an int, since JSON defines an int type and that clearly is not an int. Commented Jul 24, 2014 at 23:37
  • 1
    Then why not use the json module instead of rolling your own function? Commented Jul 24, 2014 at 23:37
  • 2
    And in general, you are presenting an XY problem. Instead of telling us what you're actually trying to do, you're telling us about a problem with your solution to what you're trying to do. Those are subtly different concepts. If what you're actually trying to do is decode JSON, then you should use the built-in tools to do so. Commented Jul 24, 2014 at 23:38

5 Answers 5

2
"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
Sign up to request clarification or add additional context in comments.

2 Comments

@user3175226 no, you're wrong, this outputs 0 for input of '0.0'.
Bear in mind that if the try block includes return, the else will never run.
1

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

Comments

1

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

4 Comments

Nope it works perfectly for me !! What was your input / which python version are you using ?
im on osx with python 2.7.5. same problem again. everything is 0
@rvraghav93 don't use is to compare equality; this only works because CPython interns small integers, an implementation detail you should not be relying on for functionality.
@jonrsharpe Okay ! Noted ! :)
0

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.

2 Comments

This will return a number or a string, which isn't terribly helpful, but more importantly claims "NOT A NUMBER!" for three of the OP's four examples.
I fixed the issues. Thought int coerced float-like-strings to the rounded down version like it does to real floats.
-1

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)

1 Comment

This is just a less efficient version of Andrew Johnson's answer; you have a minimum of three function calls for any non-empty string, and five if it's "integer-y".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.