1

I have a string that I have to convert into int or float depending or the case :

What I have    => What I want
"548189848.54" => 548189848.54
"548189848.50" => 548189848.5
"548189848.00" => 548189848

Is it possible to do it ?

Thanks,

Steve

5
  • Yes, of course its possible. What did you try? Commented Mar 7, 2014 at 13:29
  • 5
    Do you want it actually converted to an integer, or just printed with trimmed trailing zeroes? If the latter, see stackoverflow.com/questions/5807952/… Commented Mar 7, 2014 at 13:30
  • I tried float() but it works only for the two first cases. Commented Mar 7, 2014 at 13:32
  • What format is your data in? Are they in a list? Or are they individual numbers that you'd like a function to convert them with? Commented Mar 7, 2014 at 13:34
  • i think this is similar to stackoverflow.com/questions/2389846/python-decimals-format Commented Mar 7, 2014 at 13:42

9 Answers 9

2

Here's a one line that should do it.

numbers = ["548189848.54", "548189848.50", "548189848.00"]
result = [int(float(x)) if int(float(x)) == float(x) else float(x)  for x in numbers]

Gives output:

print result
[548189848.54, 548189848.5, 548189848]
Sign up to request clarification or add additional context in comments.

1 Comment

@L.Stephan it is shorter, but it's also incorrect! int("123.456") ValueError: invalid literal for int() with base 10
2

Maybe you could convert to float and then use round:

inputs = [ "548189848.54", "548189848.50", "548189848.00" ]

for i in inputs:
    f = float(i)
    if round(f) == f:
        print int(f)
    else:
        print f

output:

548189848.54
548189848.5
548189848

You could also do the same thing using a list comprehension, like:

print [int(float(i)) if round(float(i)) == float(i) else float(i) for i in inputs]

output:

[548189848.54, 548189848.5, 548189848]

Comments

0
num_str = "548189848.54"

if '.' in num_str:
    num = float(num_str)
else:
    num = int(num_str)

1 Comment

This would fail the poster's third test case. where he wanted to convert x.00 into int.
0
str_a = "23423.00"

a = float(str_a)
if a % 1.0 == 0:
    a = int(a)

2 Comments

You should add some sort of explanation along with your answer... What happens if you try "23423.000000000000000001" with your solution?
23423.000000000000000001 is not a standard python float. float("23423.000000000000000001") = 23423 (the questions wanted float or int - the required accuracy was not stated - other then float).
0

You just have to do that:

a = float("548189848.54")
a = int(a) if abs(int(a) - a) == 0 else a

2 Comments

548189848.00 is meant to be an int though
He wants to convert to int or decimal depending on whether the number is a whole number or not.
0

You'll probably get a lot of floating point precision errors if you try to do anything with Python floats. I suggest using the Decimal module:

from decimal import Decimal, getcontext
getcontext().prec = 30 # alterable, default 28
notInt = Decimal("100.000000000000000000000001")
isInt = Decimal("100.0000000000000000000000000")
if (notInt == int(notInt)):
    notInt = int(notInt)
else:
    notInt = float(notInt)

if (isInt == int(isInt)):
    isInt = int(isInt)
else:
    isInt = float(isInt)

>>> type(isInt)
<type 'int'>
>>> type(notInt)
<type 'float'>

An illustration of the floating point errors:

>>> 5.0000000000000001 == 5
True

Comments

0

Why not unnecessarily involve some regex?

import re

def float_or_int(s):
    m = re.match('([+-]?\d+)(?:\.(?:0+|$)|$)', s)
    if m:
        return int(m.group(1))
    else:
        return float(s)

With your examples:

strings = ("548189848.54", "548189848.50", "548189848.00")
map(float_or_int, strings)
# [548189848.54, 548189848.5, 548189848]

Comments

0

That is a complex script that I used for similar stuff. It used Decimal

import decimal

def remove_zeros(num):
    """
    1.100000 --> 1.1
    1.0      --> 1
    1.010    --> 1.01
    0.0      --> 0
    000.0000 --> 0
    """
    num = str(num)
    try:
        dec = decimal.Decimal(num)
    except:
        raise Exception("Not a valid floating point or integer")
    tup = dec.as_tuple()
    delta = len(tup.digits) + tup.exponent
    digits = ''.join(str(d) for d in tup.digits)
    if delta <= 0:
        zeros = abs(tup.exponent) - len(tup.digits)
        val = '0.' + ('0'*zeros) + digits
    else:
        val = digits[:delta] + ('0'*tup.exponent) + '.' + digits[delta:]
    val = val.rstrip('0')
    if val[-1] == '.':
        val = val[:-1]
    if tup.sign:
        return '-' + val
    return val

Update: @Cyber already shares the related SO post, which I failed to find.

Comments

0

This also supports lists: https://gist.github.com/pschwede/8d0f9d5f632c2f1fae17

def to_value(string):
    """Converts a string to the value it represents.
    If a non-string has been given, it stays as it is.

    Examples:
        >>> to_value("foobar")
        "foobar"
        >>> to_value(12345)
        12345
        >>> to_value("12345")
        12345
        >>> to_value("3.1415")
        3.1415
        >>> to_value("1,2,1")
        [1, 2, 1]
        >>> to_value("1,a,.5")
        [1, "a", 0.5]
    """
    # try if converting int/float back to str looks equal to the original
    # string. Return the string otherwise.
    for type_ in [int, float]:
        try:
            return type_(string)
        except ValueError:
            continue

    # if there is a comma, it must be a list
    try:
        if "," in string:
            return [to_value(s) for s in string.split(",") if s]
    except AttributeError:
        # It's not splittable. Not a string.
        return string
    except TypeError:
        # It's not iterable. Unknown type.
        return string

    # Getting here means the string couldn't be converted to something else.
    # We will return a string then.
    return string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.