Last active
August 7, 2018 13:14
-
-
Save N-McA/4a4382d2ff300a270d664afc0bcb7076 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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