Guest User

Untitled

a guest
Jun 22nd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. export function abbrieviate(value: number): string {
  2. const suffixes = ['', 'K', 'M', 'B'];
  3. const suffixNum = Math.min(Math.floor(('' + value).length / 3), 3);
  4. const shortValue = parseFloat(
  5. (suffixNum !== 0 ? value / Math.pow(1000, suffixNum) : value).toFixed(2),
  6. );
  7. return shortValue + suffixes[suffixNum];
  8. }
  9.  
  10. export function round(value: number, precision: number): number {
  11. const shift = Math.pow(10, precision);
  12. return Math.round(value * shift) / shift;
  13. }
  14.  
  15. export function sigfig(value: number, precision: number): number {
  16. const radix = Math.floor(value);
  17. const remainder = value % 1;
  18. if (radix > 0) {
  19. return round(value, Math.max(precision - radix.toString().length));
  20. } else {
  21. const firstSigFig = remainder
  22. .toString()
  23. .replace(/^0./, '')
  24. .match(/[1-9]/i);
  25. if (firstSigFig == null) {
  26. return value;
  27. }
  28. const idx = firstSigFig.index as number;
  29. return round(value, idx + precision);
  30. }
  31. }
  32.  
  33. export function formatPrice(price: number): string {
  34. const radix = Math.floor(price);
  35. const digitNum = radix.toString().length;
  36. if (digitNum > 3) {
  37. return radix.toLocaleString();
  38. } else if (digitNum <= 3 && radix !== 0) {
  39. return round(price, 2).toString();
  40. } else {
  41. return sigfig(price, 3).toString();
  42. }
  43. }
Add Comment
Please, Sign In to add comment