Skip to content

Instantly share code, notes, and snippets.

@N-McA
Last active August 7, 2018 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save N-McA/4a4382d2ff300a270d664afc0bcb7076 to your computer and use it in GitHub Desktop.
Save N-McA/4a4382d2ff300a270d664afc0bcb7076 to your computer and use it in GitHub Desktop.
function isString(s) {
return (typeof s === 'string' || s instanceof String)
}
export function toBaseUnit(value, decimals, BN) {
if (!isString(value)) {
throw new Error('Pass strings to prevent floating point precision issues.')
}
const ten = new BN(10);
const base = ten.pow(new BN(decimals));
// Is it negative?
let negative = (value.substring(0, 1) === '-');
if (negative) {
value = value.substring(1);
}
if (value === '.') {
throw new Error(
`Invalid value ${value} cannot be converted to`
+ ` base unit with ${decimals} decimals.`);
}
// Split it into a whole and fractional part
let comps = value.split('.');
if (comps.length > 2) { throw new Error('Too many decimal points'); }
let whole = comps[0], fraction = comps[1];
if (!whole) { whole = '0'; }
if (!fraction) { fraction = '0'; }
if (fraction.length > decimals) {
throw new Error('Too many decimal places');
}
while (fraction.length < decimals) {
fraction += '0';
}
whole = new BN(whole);
fraction = new BN(fraction);
let wei = (whole.mul(base)).add(fraction);
if (negative) {
wei = wei.mul(negative1);
}
return new BN(wei.toString(10), 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment