Search code examples
javascriptcurrencybitcoinconverters

Convert BTC unit and reverse it


For example, my user have following balance:

0.0022918 BTC

Now i want to make this amount like this:

2,291.80 BIT

So, i use this function:

function bitConvert(value) {
    var number = value * 100000000;
    return (number/100).toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}

Everything is good and i dont have problem.

But I dont know how can i do this opposite?

Convert 2,291.80 BIT to 0.0022918 BTC

How Can I do this ?

And I also want a solution for addition and subtraction BTC.


Solution

  • As I understood, you have a string containing your value in BIT.

    You have first to remove all the thousands separators (,), then to convert your string to a number. Finally, you have to return the resulting number (keeping a one-sat accuracy) as a string (so use toString() method).

    Here is the resulting function :

    function btcConvert(stringValue) {
        var number = Number(stringValue.replace(',','')) / 100000000;
        return number.toFixed(8).toString();
    }