-1

I am making a price ticker for reddit. Everything is working fine, but the API that it derives the price from has 4 decimal places, and a comma in it dividing the thousands.

I am just trying to figure out how to round the number to either 2 decimals, or a whole number. So far I have tried the round() function, which does not work because of the comma. I was able to remove the comma, but it still won't let me use the round function.

def main(self):
    req = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
    req = req.json()
    dollar = '1 BTC = $' + req['bpi']['USD']['rate'].replace(',' , '')

Any ideas?

SuperKogito
  • 2,998
  • 3
  • 16
  • 37
  • 1
    Did... did you convert the string to a number before calling `round` on it? – Aran-Fey Apr 06 '19 at 20:39
  • 1
    Please show us how you tried to use the round function--your given code does not attempt this. And do you want your final value for `dollar` to be a string? – Rory Daulton Apr 06 '19 at 20:43

3 Answers3

1

Maybe this could point you in the right direction!

# Original String
val_string = '19,9999'

# Replace Comma with Decimal
val_string_decimal = val_string.replace(',','.')

# Convert String to Float
val = float(val_string_decimal)

# Print Float after rounding to 2 decimal places
print(round(val, 2)) 
Will Lacey
  • 91
  • 6
0

You didn't specify whether you want to re-insert the comma after rounding. Try this:

# dummy number
str_num = "4,000.8675"
# first, remove the comma
str_num_no_comma = str_num.replace(",","")
# then, convert to float, and then round
strm_num_as_num = round(float((str_num_no_comma)))
print(strm_num_as_num)
>>> 4001.0

Of course you can cast as int if you want to ignore decimal points entirely.

zerohedge
  • 3,185
  • 4
  • 28
  • 63
0

You should usually use the Decimal class in python when playing with numbers like this-

>>> from decimal import Decimal
>>> t = '4,700.3245'
>>> Decimal(t.replace(',', '')).quantize(Decimal('1.00'))
Decimal('4700.32')

quantize is the "round" function for Decimal objects- it will round to the same number of decimal places as the Decimal object passed as an argument.

Paul Becotte
  • 9,767
  • 3
  • 34
  • 42