0

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))

1 Answer 1

1

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

1 Comment

its the simple things that please me!

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.