Skip to content

Instantly share code, notes, and snippets.

@0ex-d
Created December 27, 2021 11:13
Show Gist options
  • Save 0ex-d/85afd4f6e333dad7dfe091f7af48fe0e to your computer and use it in GitHub Desktop.
Save 0ex-d/85afd4f6e333dad7dfe091f7af48fe0e to your computer and use it in GitHub Desktop.
Properly handle crypto currency and stable coins value in large decimals
import BigNumber = require('bignumber.js');
/** Format a value in crypto or stablecoin equivalent */
function cryptoFormat(numeric: string | number): number {
try {
const num = typeof numeric === 'string' ? Number(numeric) : numeric;
if (!Number.isNaN(num)) {
throw new TypeError('Amount should be a number');
}
return new BigNumber(num).toNumber();
} catch (e) {
console.error(e, { tag: 'cryptoFormat' });
return 0;
}
}
// e.g
// cryptoFormat(0.56)
// cryptoFormat('0.000321')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment