cool_jesus
cool_jesus

Reputation: 197

Inteligently remove ".0" from float output

I have such slice of result of my function:

{
    "id": "7418", 
    "name": "7.5"
}, 
{
    "id": "7419", 
    "name": "8.0"
}, 
{
    "id": "7420", 
    "name": "8.5"
}, 
{
    "id": "7429", 
    "name": "9.0"
}, 

I am doing simply:

[{'id': opt['size'], 'name': '{}'.format(float(opt['value']))} for opt in options]

I don't want to make any replacements of ".0", I'm interested in how to convert data correctly to:

{
    "id": "7429", 
    "name": "9"
}

Upvotes: 0

Views: 1568

Answers (4)

Vivek Sable
Vivek Sable

Reputation: 10223

As type value of name is String, so we can use split method also

Demo:

input_list = [{'id': '7418', 'name': '7.5'}, {'id': '7419', 'name': '8.0'}, {'id': '7420', 'name': '8.5'}, {'id': '7429', 'name': '9.0'}]

result = []

for i in input_list:
    # Split by .
    tmp = i["name"].split(".")
    try:
        #- Type casting.
        tmp1 = int(tmp[1])
    except IndexError:
        result.apend({"id":i["id"], "name":i["name"]})
        continue
    except ValueError:
        print "Value exception, Check input:-", i
        continue

    #- Check after decimal number is equal to 0 or not.
    if tmp1==0:
        val = tmp[0]
    else:
        val = i["name"]
    result.append({"id":i["id"], "name":val})


print "Result:-", result

output:

Result:- [{'id': '7418', 'name': '7.5'}, {'id': '7419', 'name': '8'}, {'id': '7420', 'name': '8.5'}, {'id': '7429', 'name': '9'}]

Upvotes: 0

Format your number with .15g

>>> format(555.123, '.15g')
555.123
>>> format(5.0, '.15g')
5

Though it will use the scientific exponent format for numbers close to zero:

>>> format(0.00001, '.16g')
1e-05

and for numbers that have 16+ digits before decimal point.

Note that you do not need to use the '{}'.format(); format built-in function as above works better here.

Upvotes: 3

Malik Brahimi
Malik Brahimi

Reputation: 16721

Well, if that is a list of dictionaries:

[{'id': i['id'], 'name': ['{:.1f}', '{:.0f}'][float(i['name']).is_integer()].format(float(i['name']))} for i in your_list]

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 122154

If you want to convert only float objects that represent integers to int (i.e. convert 9.0 to 9 but leave 9.5 as it is), you can use float.is_integer to check:

>>> numbers = [1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
>>> numbers = map(lambda f: int(f) if f.is_integer() else f, numbers)
>>> numbers
[1, 1.2, 1.4, 1.6, 1.8, 2]
>>> map(type, numbers)
[<type 'int'>, <type 'float'>, <type 'float'>, <type 'float'>, <type 'float'>, <type 'int'>]

Alternatively, if you want to apply the conversion to the string (i.e. without converting the JSON to Python objects), you could use a regular expression (see demo):

>>> import re
>>> data = """
             {
                 "id": "7418", 
                 "name": "7.5"
             }, 
             {
                 "id": "7419", 
                 "name": "8.0"
             }, """
>>> print re.sub(r'"(\d+)\.0"', r'"\1"', data)

             {
                 "id": "7418", 
                 "name": "7.5"
             }, 
             {
                 "id": "7419", 
                 "name": "8"
             }, 

Note again that "7.5" is untouched, but "8.0" is replaced with "8".

Upvotes: 1

Related Questions