DEV Community

charles
charles

Posted on

Building a Bitcoin Calculator with Javascript

Introduction

Hey guys, I am going to show you how to use Bitcoin exchange rates and currency conversion that supports all major currencies. I am currently using Coindesk which provides API to make data programmatically available to others.

To use the API, you don't need to register, it is free!

You can check out the supported currencies available on their website (http://coindesk.com). To use the endpoint, you make a request to:

https://api.coindesk.com/v1/bpi/currentprice/[code].json

The code parameter accepts a valid ISO 4217 currency code

A sample request

sample

Take a look at the result, you would notice the rate and the rate_float object, which contains the exchange rate for the local currency to BTC. Below is a formula to convert BTC to your local currency.

Formula = BTC Amount * Exchange Rate = Local currency Price

Building the Bitcoin Calculator

Using a client to consume the JSON data returned from the endpoint is the first thing to do. You can use Asp.Net HttpClient class, Jquery getJson() function which we are going to use here or you can use others you already know.

$.getJSON( "https://api.coindesk.com/v1/bpi/currentprice/usd.json", function( data) {
   var amountInBtc = 0.005; //convert 0.005 btc to usd
   var exchangeRate = parseInt(data.bpi.USD.rate_float);
   var amount = amountInBtc * exchangeRate;
   console.log(amount);
});
Enter fullscreen mode Exit fullscreen mode

Follow Me:

Blog: https://techcerberus.blogspot.com
Twitter: https://twitter.com/charlesnnaji
Medium: https://medium.com/@cizu64

Top comments (3)

Collapse
 
nrobinson2000 profile image
Nathan Robinson

I've been maintaining a project for awhile that allows users to create bitcoin donation pages using JQuery. It features a QR code generator, multiple fiat currencies, and a clickable link generator. Best of all, parameters can be overridden via URL queries.

github.com/nrobinson2000/donate-bi...

You can see it in action here:
donate.nrobinson.me/

Collapse
 
cryptokit profile image
CryptoKit

nice, like the bitcoin calc, very useful.

Collapse
 
levelcoding profile image
levelcoding

you have someting what called currency valute?