Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const BN = require('bn.js');
const stripHexPrefix = val => typeof val === 'string' && val.indexOf('0x') === 0 ? val.slice(2) : val;
const hexPrefix = val => val ? (`0x${stripHexPrefix((val || {}).div ? val.toString(16) : val)}`) : val;
const hexToBN = val => (val || {}).div ? val : new BN(stripHexPrefix(hexPrefix(val)), 16);
const numToBN = val => (val || {}).div || String(val).indexOf('0x') !== -1 ? hexToBN(val) : new BN(val, 10);
function intToDecimal(weiInput, baseLength, optionsInput) {
var wei = numToBN(weiInput); // eslint-disable-line
var negative = wei.lt(new BN(0)); // eslint-disable-line
const base = (new BN(10, 10)).pow(numToBN(baseLength));
const options = optionsInput || {};
if (negative) {
wei = wei.mul(new BN(-1));
}
var fraction = wei.mod(base).toString(10); // eslint-disable-line
while (fraction.length < baseLength) {
fraction = `0${fraction}`;
}
if (!options.pad) {
fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
}
var whole = wei.div(base).toString(10); // eslint-disable-line
if (options.commify) {
whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
var value = `${whole}${fraction == '0' ? '' : `.${fraction}`}`; // eslint-disable-line
if (negative) {
value = `-${value}`;
}
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.