Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export class UnitProvider {
- postfixes: string[];
- constructor() {
- let lang = localStorage.getItem('lang');
- if (lang === 'zh-TW') {
- this.postfixes = ['', '', '', '', 'θ¬', '', '', '', '', '', '', '', '', '', '', ''];
- } else if (lang === 'zh-CN') {
- this.postfixes = ['', '', '', '', 'δΈ', '', '', '', '', '', '', '', '', '', '', ''];
- } else {
- this.postfixes = ['', '', '', 'K', '', '', 'M', '', '', 'G', '', '', 'T', '', '', 'P', '', '', 'E'];
- }
- }
- }
- export interface IShortenNumberOptions {
- precision?: number,
- appendComma?: boolean,
- appendPostfix?: boolean,
- trailing?: boolean,
- }
- export class ShortenNumberFormater {
- options: IShortenNumberOptions = {
- precision: 0,
- appendComma: true,
- appendPostfix: true,
- trailing: true
- };
- postfixes: string[];
- trailing: boolean = true;
- constructor(options?: IShortenNumberOptions) {
- Object.assign(this.options, options || {});
- let unitProvider = new UnitProvider();
- this.postfixes = unitProvider.postfixes;
- }
- format(value: number) {
- let precision = this.options.precision;
- let appendComma = this.options.appendComma;
- let appendPostfix = this.options.appendPostfix;
- let trailing = this.options.trailing;
- let decimal,
- unit,
- newValue = value;
- for (let i = this.postfixes.length - 1; i >= 0; i--) {
- unit = this.postfixes[i];
- if (unit === '') {
- continue;
- }
- decimal = Math.pow(10, i);
- if (Math.abs(value) >= decimal) {
- newValue = (value / decimal);
- break;
- }
- }
- let formatted;
- if (appendComma) {
- formatted = newValue.toLocaleString('en', { minimumFractionDigits: precision, maximumFractionDigits: precision })
- } else {
- formatted = newValue.toFixed(precision);
- }
- if (trailing) { formatted = formatted.replace(/\.0+$/, ''); }
- if (appendPostfix) { formatted += unit; }
- return formatted;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement