Display current bitcoin price chat command

Asked Feb 28, 2021·5 replies·Last activity 5 years ago·Open in Discord ↗
Archived from the original community forum
Things may have changed since it was written. Still stuck? Ask the community on Discord.

I made a chat command that uses api info from blockchain.info to display the current price of bitcoin in twitch chat.

This is the script for it

" The current price of bitcoin is $$(eval 1/$(urlfetch json https://blockchain.info/tobtc?currency=USD&value=1)) "

This works by taking how much bitcoin can be bought with $1 then doing 1 divided by that number. It works fine but it displays the number to 12 decimal places.

Does anyone know how I can trim the result down to only 2 decimal places?

Thanks.

5 replies

We can use the JavaScript toFixed method. If x is a number then x.toFixed(n) is a string representing x rounded to n decimals.

Hi thanks for the reply, I found similar answers using x.toFixed(n) online but i'm not sure where exactly that line goes in relation to my command script.

Would it go something like '$(eval 1/$(urlfetch json API_LINK_HERE)).toFixed(2)' for 2 decimal places?

Hey there! The forums are saying I can't post links...was going to give some examples with API calls 😦 I'll try to help without the links, though.

The link you posted originally is not a JSON file, so you don't need the JSON parameter. You're only getting text back, specifically a string. toFixed(2) has to be ran on a number datatype --so either an integer or a float --probably a float if you're working with decimals. This is my sample code (with links removed b/c the forums are yelling at me for links) using Coinbase -the Coinbase file is a JSON file, but the data I get is a string similar to yours.

$(eval let api=$(urlfetch json \<URL\>); let amt=parseFloat(api.data.amount); amt.toFixed(2); )

To see what data type my data was I used (again with links removed 😑):
$(eval let api=$(urlfetch json \<URL\>); typeof api.data.amount;)

EDIT: I just tested with the URL you provided and it is a number!
$(eval let info=$(urlfetch \<URL\>); typeof info;)

I suggest just storing what the urlfetch catches in a variable, then called .toFixed(2) on that variable.

However....if you're trying to get the price one 1 BTC in USD...I think the link you shared is showing how much 1 USD is in BTC. It is a very small number and toFixed(2) returns 0.00 because it is so small.

Yes the reason I used a link that tells how much BTC you get with $1 is because I could not find an API link that just spits out the BTC price on its own. So my solution was to use that link to calculate how much $1 buys then do 1 divided by that number. So I already have the correct number I just need to convert it to 2 decimal places. I'll try some of the ones you suggested thanks.

Didn't find your answer? The community is on Discord.

Ask on Discord