super-hero/assets/cc-common/cc-util/UmMoneyFormat.ts

98 lines
2.8 KiB
TypeScript

import { UmConfig } from './UmConfig';
declare global {
interface Number {
toMoneyKMB(digits: number): string;
toStringWithPlusSymbol(isPlusZero?: boolean): string;
formatMoney(): string;
formatInt(): string;
formatNumberLessThan10(): string;
formatMoneyKMB(): string;
formatMoneyInTable(): string;
pformatMoneyWC(): string;
}
}
Number.prototype.toMoneyKMB = function (digits: number): string {
var si = [
{ value: 1, symbol: "" },
{ value: 1E3, symbol: "K" },
{ value: 1E6, symbol: "M" },
{ value: 1E9, symbol: "B" },
{ value: 1E12, symbol: "T" },
{ value: 1E15, symbol: "P" },
{ value: 1E18, symbol: "E" }
];
var rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
var i;
let number = Number(this);
let abs_number = Math.abs(number);
for (i = si.length - 1; i > 0; i--) {
if (abs_number >= si[i].value) {
break;
}
}
return (number / si[i].value).truncDigits(digits).toString().replace(rx, "$1") + si[i].symbol;
}
Number.prototype.toStringWithPlusSymbol = function (isPlusZero?: boolean): string {
if (isPlusZero) {
return this >= 0 ? `+${this.formatMoneyInTable()}` : this.formatMoneyInTable();
}
else {
return this > 0 ? `+${this.formatMoneyInTable()}` : this.formatMoneyInTable();
}
}
Number.prototype.formatMoney = function (): string {
// let format = Number(this).truncDigits(4).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
let str = Number(this).truncDigits(UmConfig.digitRound).toString();
let regx = /(\d{1,3})(\d{3}(?:,|$))/;
let currStr;
do {
currStr = (currStr || str.split(`.`)[0]).replace(regx, `$1,$2`)
} while (currStr.match(regx)) //Stop when there's no match & null's returned
return (str.split(`.`)[1]) ? currStr.concat(`.`, str.split(`.`)[1]) : currStr;
}
Number.prototype.formatInt = function (): string {
return Number(this).roundDigits(0).toLocaleString('en-US');
}
Number.prototype.formatNumberLessThan10 = function (): string {
return ('0' + Number(this)).slice(-2);
}
Number.prototype.formatMoneyKMB = function (): string {
if (UmConfig.isRoundMoney) {
return Number(this).toMoneyKMB(1);
}
else {
return Number(this).formatMoney();
}
}
Number.prototype.formatMoneyInTable = function (): string {
let number = Number(this);
if (UmConfig.isRoundMoney) {
if (Math.abs(number) < 10000) {
return number.formatMoney();
}
else {
return number.toMoneyKMB(1);
}
}
else {
if (Math.abs(number) < 1000) {
return number.formatMoney();
}
else {
return number.toMoneyKMB(1);
}
}
}
Number.prototype.pformatMoneyWC = function (): string {
return Number(this).formatMoney();
}