Skip to content

Instantly share code, notes, and snippets.

@hagi4u
Created March 13, 2020 05:26
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 hagi4u/a0d5d60afac17deef898f6a3e2600631 to your computer and use it in GitHub Desktop.
Save hagi4u/a0d5d60afac17deef898f6a3e2600631 to your computer and use it in GitHub Desktop.
getNumberSIPrefix.js
export function getNumberSIPrefix(x, options = {}) {
const FLOAT_POINT = options.floatLength || 1;
const METIRC_GAP = options.metircGap || 1;
const UNITS_STRING = [
'million',
'billion',
'trillion',
'quadrillion',
'quintillion',
'sextillion',
'septillion',
'octillion',
'nonillion',
'decillion',
'undecillion',
'duodecillion',
'tredecillion',
'quattuordecillion',
'quindecillion',
'sexdecillion',
'septendecillion',
'octodecillion',
'novemdecillion',
'vigintillion',
];
const originNumberString = x.toLocaleString().replace(/(\,)/gi, '');
const originNumberStringLength = originNumberString.length - 1;
const unitIndex = originNumberStringLength / 3;
// 10^0, 10^3 은 생략 (UNIT_STRING.length -2)
const unit = UNITS_STRING[Math.floor(unitIndex) - 2 - METIRC_GAP];
// units 의 규칙인 10^3n 승에 대해 남은 자릿수를 알게 하려 함
// 딱 맞아 떨어지게 되면 자리수가 0개 가는건 오류이므로 +1 처리
const substrLength = (originNumberStringLength % 3) + 1 + 3 * METIRC_GAP;
const decimal = originNumberString.substr(0, unit && substrLength);
const float = originNumberString.substr(substrLength, FLOAT_POINT);
const combined = +`${decimal}.${float}`;
return `${parseFloat(combined).toLocaleString()} ${unit || ''}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment