2018-12-09 14:36:18 +01:00
|
|
|
import * as numeral from 'numeral';
|
2018-09-12 17:53:08 +02:00
|
|
|
import 'numeral/locales/bg';
|
|
|
|
import 'numeral/locales/cs';
|
|
|
|
import 'numeral/locales/da-dk';
|
|
|
|
import 'numeral/locales/de';
|
|
|
|
import 'numeral/locales/en-au';
|
|
|
|
import 'numeral/locales/en-gb';
|
|
|
|
import 'numeral/locales/es';
|
|
|
|
import 'numeral/locales/fr';
|
|
|
|
import 'numeral/locales/hu';
|
|
|
|
import 'numeral/locales/it';
|
|
|
|
import 'numeral/locales/lv';
|
|
|
|
import 'numeral/locales/no';
|
|
|
|
import 'numeral/locales/pl';
|
|
|
|
import 'numeral/locales/ru';
|
|
|
|
|
2018-09-12 18:19:59 +02:00
|
|
|
/* eslint-disable class-methods-use-this */
|
|
|
|
|
2018-09-12 17:53:08 +02:00
|
|
|
class NumeralFormatter {
|
2018-12-09 14:36:18 +01:00
|
|
|
// Default Locale
|
|
|
|
defaultLocale: string = "en";
|
|
|
|
|
2018-09-12 18:19:59 +02:00
|
|
|
constructor() {
|
|
|
|
this.defaultLocale = 'en';
|
|
|
|
}
|
|
|
|
|
2018-12-09 14:36:18 +01:00
|
|
|
updateLocale(l: string): boolean {
|
2018-09-12 17:53:08 +02:00
|
|
|
if (numeral.locale(l) == null) {
|
|
|
|
console.warn(`Invalid locale for numeral: ${l}`);
|
|
|
|
|
2018-09-12 18:19:59 +02:00
|
|
|
numeral.locale(this.defaultLocale);
|
2018-09-12 17:53:08 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2018-12-09 14:36:18 +01:00
|
|
|
format(n: number, format: string): string {
|
2018-11-21 06:43:15 +01:00
|
|
|
// numeraljs doesnt properly format numbers that are too big or too small
|
|
|
|
if (Math.abs(n) < 1e-6) { n = 0; }
|
2021-03-20 04:08:41 +01:00
|
|
|
const answer = numeral(n).format(format);
|
|
|
|
if (answer === 'NaN') {
|
|
|
|
return `${n}`;
|
|
|
|
}
|
|
|
|
return answer;
|
2018-09-12 17:53:08 +02:00
|
|
|
}
|
2019-01-09 01:41:42 +01:00
|
|
|
|
2019-01-15 04:34:04 +01:00
|
|
|
formatBigNumber(n: number): string {
|
|
|
|
return this.format(n, "0.000a");
|
|
|
|
}
|
|
|
|
|
2019-01-09 01:41:42 +01:00
|
|
|
formatMoney(n: number): string {
|
|
|
|
return this.format(n, "$0.000a");
|
|
|
|
}
|
2019-01-09 11:06:49 +01:00
|
|
|
|
2019-01-15 04:34:04 +01:00
|
|
|
formatPercentage(n: number, decimalPlaces: number=2): string {
|
|
|
|
const formatter: string = "0." + "0".repeat(decimalPlaces) + "%";
|
|
|
|
return this.format(n, formatter);
|
2019-01-09 11:06:49 +01:00
|
|
|
}
|
2019-01-15 04:34:04 +01:00
|
|
|
|
|
|
|
|
2018-09-12 17:53:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export const numeralWrapper = new NumeralFormatter();
|