Skip to content

Instantly share code, notes, and snippets.

@diranl
Created June 21, 2018 01:26
Show Gist options
  • Save diranl/f2f876a4f5a063b96aa7af6d582d3aee to your computer and use it in GitHub Desktop.
Save diranl/f2f876a4f5a063b96aa7af6d582d3aee to your computer and use it in GitHub Desktop.
export function abbrieviate(value: number): string {
const suffixes = ['', 'K', 'M', 'B'];
const suffixNum = Math.min(Math.floor(('' + value).length / 3), 3);
const shortValue = parseFloat(
(suffixNum !== 0 ? value / Math.pow(1000, suffixNum) : value).toFixed(2),
);
return shortValue + suffixes[suffixNum];
}
export function round(value: number, precision: number): number {
const shift = Math.pow(10, precision);
return Math.round(value * shift) / shift;
}
export function sigfig(value: number, precision: number): number {
const radix = Math.floor(value);
const remainder = value % 1;
if (radix > 0) {
return round(value, Math.max(precision - radix.toString().length));
} else {
const firstSigFig = remainder
.toString()
.replace(/^0./, '')
.match(/[1-9]/i);
if (firstSigFig == null) {
return value;
}
const idx = firstSigFig.index as number;
return round(value, idx + precision);
}
}
export function formatPrice(price: number): string {
const radix = Math.floor(price);
const digitNum = radix.toString().length;
if (digitNum > 3) {
return radix.toLocaleString();
} else if (digitNum <= 3 && radix !== 0) {
return round(price, 2).toString();
} else {
return sigfig(price, 3).toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment