johnashu
johnashu

Reputation: 2211

JSON Python, String to Float conversion or operand. API DATA

I wish to change JSON data to a float for calculating the price of bitcoin so I can continue with other calculations..

I have made a whole load of calculating methods and if i replace currency variable with an int or float it works fine.

Only when i get the json data from the api do i have problems..

i receive the following error with

e_b = float(btc) / float(cur)

TypeError: unsupported operand type(s) for /: 'float' and 'str'

and with simply

 e_b = btc / cur

i get

ValueError: could not convert string to float: '2,541.6300'

Here is the problem code. everything runs fine afterwards if a float or int is given..

import requests
import json

cur_price_url = "http://api.coindesk.com/v1/bpi/currentprice.json"

def bitcoin_current_price(url):
    """
        Function to return json data from API
        “Powered by CoinDesk” http://www.coindesk.com/price/
    """
    return requests.get(url).json()
btc_price = (bitcoin_current_price(cur_price_url))

def btc_cur():
    """  Displays Different Currency Rates and Information """
    print('\n\n USD: ' + str(btc_price['bpi']['USD']['rate']))
    print('\n\n EUR: ' + str(btc_price['bpi']['EUR']['rate']))
    print('\n\n GBP: ' + str(btc_price['bpi']['GBP']['rate']))
btc_cur()

bitcoin_usd = str(btc_price['bpi']['USD']['rate'])
bitcoin_eur = str(btc_price['bpi']['USD']['rate'])
bitcoin_gbp = str(btc_price['bpi']['USD']['rate'])

btc = 1
currency = 123.32
amount = 1

def cur_name():
    """ Name the Currencies """
    if currency == bitcoin_usd:
        cur_prt = "USD"
    elif currency == bitcoin_gbp:
        cur_prt = "GBP"
    else:
        cur_prt = "EUR"
    return cur_prt

def convert(cur, num):
    """simple conversion between currencies"""
    e_b = btc / cur
    print('\n' + str(1) + " " + str(cur_name()) + " is " + str(e_b) + " BTC")
    print(str(1) + " BTC" + " is " + str(cur) + ' ' + str(cur_name()) + '\n')

    e_b_con = e_b * num
    return e_b_con

print(convert(currency, amount))

Upvotes: 0

Views: 203

Answers (1)

Qeek
Qeek

Reputation: 1970

The value of cur = 2,541.6300 is not valid float number and so Python cannot convert it automatically. You have to change it into the form of xxx.yy.

Here is one way how to do it:

e_b = btc / float(cur.replace(",",""))

Upvotes: 1

Related Questions