@triplespeeder/bn2string

1.0.0 • Public • Published

bn2string

Provide ready-to-use display strings for BN.js instances.

Installation

npm install @triplespeeder/bn2string

Usage

Assume we have a balance of around 12500 Tether (USDT) tokens. USDT is specified with 6 decimals. For display in a GUI we want to have the human-readable USDT value, both rounded to 2 decimals and in full precision.

var BN = require('bn.js')
var bn2DisplayString = require('@triplespeeder/bn2string')

const value = new BN('12525652700')
const decimals = new BN('6')
const roundToDecimals = new BN('2')

var {precise, rounded} = bn2DisplayString({value, decimals, roundToDecimals})

console.log("Precise balance: " + precise + " USDT")
console.log("Rounded balance: " + rounded + " USDT")

Output:

[michael]$ node example.js
Precise balance: 12 525.652700 USDT
Rounded balance: 12 525.65 USDT

Changing the decimal separator

By default '.' is used as decimal separator. This can be changed by providing a different symbol, e.g.

var {precise, rounded} = bn2DisplayString({value, decimals, roundToDecimals, decimalSeparator:','})

Output:

[michael]$ node example.js
Precise balance: 12 525,652700 USDT
Rounded balance: 12 525,65 USDT

Changing digit grouping

By default the integer digits are grouped as triplets and separated by unicode symbol u202F, the "narrow no-break space" (See https://en.wikipedia.org/wiki/Decimal_separator#Digit_grouping for reasoning). This can be changed with the optional parameter 'groupSeparator':

var {precise, rounded} = bn2DisplayString({value, decimals, roundToDecimals, groupSeparator: ','})

Output:

[michael]$ node example.js
Precise balance: 12,525.652700 USDT
Rounded balance: 12,525.65 USDT

Package Sidebar

Install

npm i @triplespeeder/bn2string

Weekly Downloads

0

Version

1.0.0

License

MIT

Unpacked Size

16.7 kB

Total Files

4

Last publish

Collaborators

  • triplespeeder