-2

I am a beginner and need help with converting str to float on python.

the code seems to work fine locally, but when I deploy on heroku I get

"ValueError: could not convert string to float".

Is anybody else experiencing this? It would be great if you could help me.

2022-01-26T14:40:03.536858+00:00 app[web.1]:
tx_count = float(raw_data["result"].replace("0x", ""))
2022-01-26T14:40:03.536858+00:00 app[web.1]:

#ValueError: could not convert string to float: 'Invalid API Key'

my code:

my_address = request.form["public_key"]
response = requests.get(f"https://api.etherscan.io/api?module=proxy&action=eth_getTransactionCount&address={my_address}&tag=latest&apikey={API_KEY}")
raw_data = response.json()

raw_data:

raw_data = {
 'jsonrpc': '2.0', 
 'id': 1, 
 'result': '0x3'
} 

I want raw_data["result"] to be a number because I want to use the number to calculate.

I created a repository on github https://github.com/yataishiba/co2-calc-eth

UPDATE I tried this but it is still not working... Convert hex string to int in Python

zceimiz
  • 1
  • 1
  • 3
    we have no idea what `raw_data['result']` is. All we know is that it can't be converted to a float. Please read [mcve] – DeepSpace Jan 26 '22 at 14:48
  • okay so raw_data = {'jsonrpc': '2.0', 'id': 1, 'result': '0x3'} and I am using .replace to remove "0x" so that I can get 3. But since 3 is a string, I wanna convert it to a number so that I can use it to calculate. I just edited but question so that you can see my code. – zceimiz Jan 26 '22 at 18:09

1 Answers1

1

You can't throw hex directly at float() because the string can contain non-numerical strings; i.e. A-F.

Instead you should use float.fromhex(). This will also let you not use .replace(). For example:

tx_count = float.fromhex(raw_data["result"])
BTables
  • 4,413
  • 2
  • 11
  • 30
  • If I try that I get ValueError: invalid hexadecimal floating-point string – zceimiz Jan 26 '22 at 18:15
  • @zceimiz I would double check what data you're passing to it, then. Because `float.fromhex('0x3')` is definitely valid. – BTables Jan 26 '22 at 18:28
  • its working fine locally... but when I deploy it on heroku it gives me ```2022-01-26T19:06:19.611150+00:00 app[web.1]: tx_count = float.fromhex(tx) 2022-01-26T19:06:19.611151+00:00 app[web.1]: ValueError: invalid hexadecimal floating-point string``` – zceimiz Jan 26 '22 at 19:08
  • okay so it termed out that raw_data["result"] was not invalid so the above code did not work. thank you so much for the help – zceimiz Jan 26 '22 at 23:06