bitcoin-units
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

bitcoin-units

Build Status codecov npm version npm Twitter Follow

Convert between any bitcoin unit - BTC, mBTC, μBTC, satoshi and even your own custom units.

new BitcoinUnit(10000, 'sats').to('BTC').getValue();
// 0.001;

new BitcoinUnit(21000, 'sats').to('BTC').format();
// '0.00021000 BTC';

👉 Try the demo

Installation

Add bitcoin-units to your Javascript project dependencies using Yarn:

yarn add bitcoin-units

Or NPM:

npm install bitcoin-units --save

Usage

Importing

Import using ESM:

import BitcoinUnit from 'bitcoin-units';

Or CJS:

const BitcoinUnit = require('bitcoin-units');

Converting bitcoin

Basic unit conversions are done using the to(unit) function:

new BitcoinUnit(1, 'mBTC').to('BTC').getValue();
// 0.001;

Available units

There are 4 available units by default: btc, mbtc, bit and satoshi.

You can also use any of the following aliases:

  • btc: bitcoinor bitcoins

  • mbtc: millibtc

  • bit: microbtc

  • sats: sat, satoshi, satoshis

Available getters

getValue() returns a Number:

new BitcoinUnit(1, 'mBTC').to('BTC').value();
// 0.001;

toString() returns a string:

new BitcoinUnit(100000, 'satoshi').to('BTC').toString();
// '0.001';

format() returns a string with the value and unit:

new BitcoinUnit(100000, 'satoshi').to('BTC').format();
// '0.00100000 BTC';

Customization

Custom Format

You can set your own custom formats using the BitcoinUnit.setDisplay(unit, options):

BitcoinUnit.setDisplay('sats', {
  format: '{amount} something',
});

new BitcoinUnit(1, 'BTC').to('satoshi').format();

// '100,000,000 something';

Custom Unit

If you want to create your own custom units, you can use the bitcoin.setUnit(unit, value):

BitcoinUnit.setUnit('custom', 1 / 1e2);

new BitcoinUnit(1, 'btc').to('custom').value();

// 100;

You can use this to create your own conversion to fiat currencies:

// Let's suppose a rate of 1 BTC = $8000.00

BitcoinUnit.setUnit('usd', 1 / 8000);

new BitcoinUnit(1, 'satoshi').to('usd').value();

// 0.00008;

There's a shorthand to this function named bitcoin.setFiat(unit, rate):

BitcoinUnit.setFiat('usd', 8000);

new BitcoinUnit(1, 'satoshi').to('usd').value();

// 0.00008;

Author

Rui Gomes
https://ruigomes.me

License

The MIT License (MIT). Please see LICENSE file for more information.

Package Sidebar

Install

npm i bitcoin-units

Weekly Downloads

237

Version

1.0.0

License

MIT

Unpacked Size

189 kB

Total Files

39

Last publish

Collaborators

  • ruigomes