UNPKG

2.64 kBMarkdownView Raw
1# Unit
2
3Unit is a utility for handling and converting bitcoin units. We strongly recommend to always use satoshis to represent amount inside your application and only convert them to other units in the front-end.
4
5To understand the need of using the `Unit` class when dealing with unit conversions, see this example:
6
7```javascript
8> 81.99 * 100000 // wrong
98198999.999999999
10> var bitcore = require('bitcore');
11> var Unit = bitcore.Unit;
12> Unit.fromMilis(81.99).toSatoshis() // correct
138199000
14```
15
16## Supported units
17
18The supported units are BTC, mBTC, bits (micro BTCs, uBTC) and satoshis. The codes for each unit can be found as members of the Unit class.
19
20```javascript
21var btcCode = Unit.BTC;
22var mbtcCode = Unit.mBTC;
23var ubtcCode = Unit.uBTC;
24var bitsCode = Unit.bits;
25var satsCode = Unit.satoshis;
26```
27
28## Creating units
29
30There are two ways for creating a unit instance. You can instantiate the class using a value and a unit code; alternatively if the unit it's fixed you could you some of the static methods. Check some examples below:
31
32```javascript
33var unit;
34var amount = 100;
35
36// using a unit code
37var unitPreference = Unit.BTC;
38unit = new Unit(amount, unitPreference);
39
40// using a known unit
41unit = Unit.fromBTC(amount);
42unit = Unit.fromMilis(amount);
43unit = Unit.fromBits(amount);
44unit = Unit.fromSatoshis(amount);
45```
46
47## Conversion
48
49Once you have a unit instance, you can check its representation in all the available units. For your convenience the classes expose three ways to accomplish this. Using the `.to(unitCode)` method, using a fixed unit like `.toSatoshis()` or by using the accessors.
50
51```javascript
52var unit;
53
54// using a unit code
55var unitPreference = Unit.BTC;
56value = Unit.fromSatoshis(amount).to(unitPreference);
57
58// using a known unit
59value = Unit.fromBTC(amount).toBTC();
60value = Unit.fromBTC(amount).toMilis();
61value = Unit.fromBTC(amount).toBits();
62value = Unit.fromBTC(amount).toSatoshis();
63
64// using accessors
65value = Unit.fromBTC(amount).BTC;
66value = Unit.fromBTC(amount).mBTC;
67value = Unit.fromBTC(amount).bits;
68value = Unit.fromBTC(amount).satoshis;
69```
70
71## Using a fiat currency
72
73The unit class also provides a convenient alternative to create an instance from a fiat amount and the corresponding BTC/fiat exchange rate. Any unit instance can be converted to a fiat amount by providing the current exchange rate. Check the example below:
74
75```javascript
76var unit, fiat;
77var amount = 100;
78var exchangeRate = 350;
79
80unit = new Unit(amount, exchangeRate);
81unit = Unit.fromFiat(amount, exchangeRate);
82
83fiat = Unit.fromBits(amount).atRate(exchangeRate);
84fiat = Unit.fromBits(amount).to(exchangeRate);
85```