Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. export class UnitProvider {
  2. postfixes: string[];
  3.  
  4. constructor() {
  5. let lang = localStorage.getItem('lang');
  6. if (lang === 'zh-TW') {
  7. this.postfixes = ['', '', '', '', '萬', '', '', '', '', '', '', '', '', '', '', ''];
  8. } else if (lang === 'zh-CN') {
  9. this.postfixes = ['', '', '', '', 'δΈ‡', '', '', '', '', '', '', '', '', '', '', ''];
  10. } else {
  11. this.postfixes = ['', '', '', 'K', '', '', 'M', '', '', 'G', '', '', 'T', '', '', 'P', '', '', 'E'];
  12. }
  13. }
  14. }
  15.  
  16. export interface IShortenNumberOptions {
  17. precision?: number,
  18. appendComma?: boolean,
  19. appendPostfix?: boolean,
  20. trailing?: boolean,
  21. }
  22.  
  23. export class ShortenNumberFormater {
  24. options: IShortenNumberOptions = {
  25. precision: 0,
  26. appendComma: true,
  27. appendPostfix: true,
  28. trailing: true
  29. };
  30. postfixes: string[];
  31. trailing: boolean = true;
  32.  
  33. constructor(options?: IShortenNumberOptions) {
  34. Object.assign(this.options, options || {});
  35. let unitProvider = new UnitProvider();
  36. this.postfixes = unitProvider.postfixes;
  37. }
  38.  
  39. format(value: number) {
  40. let precision = this.options.precision;
  41. let appendComma = this.options.appendComma;
  42. let appendPostfix = this.options.appendPostfix;
  43. let trailing = this.options.trailing;
  44.  
  45. let decimal,
  46. unit,
  47. newValue = value;
  48.  
  49. for (let i = this.postfixes.length - 1; i >= 0; i--) {
  50. unit = this.postfixes[i];
  51. if (unit === '') {
  52. continue;
  53. }
  54.  
  55. decimal = Math.pow(10, i);
  56. if (Math.abs(value) >= decimal) {
  57. newValue = (value / decimal);
  58. break;
  59. }
  60. }
  61. let formatted;
  62. if (appendComma) {
  63. formatted = newValue.toLocaleString('en', { minimumFractionDigits: precision, maximumFractionDigits: precision })
  64. } else {
  65. formatted = newValue.toFixed(precision);
  66. }
  67. if (trailing) { formatted = formatted.replace(/\.0+$/, ''); }
  68. if (appendPostfix) { formatted += unit; }
  69.  
  70. return formatted;
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement