tachybase_todo/packages/plugins/@hera/plugin-rental/src/utils/currencyUtils.ts

88 lines
2.2 KiB
TypeScript
Raw Permalink Normal View History

2024-03-07 20:55:41 +08:00
export enum FormatType {
/**
*
*/
currency = 'currency',
/**
*
*/
percent = 'percent',
/**
*
*/
quantity = 'quantity',
}
/**
*
* @param _number
* @param fractionDigits
* @param formatType : 'currency' | 'percent' | 'quantity' /
* @returns
*/
const format = (_number: number, fractionDigits: number, formatType: FormatType): string => {
const number = typeof _number === 'undefined' || Number.isNaN(_number) ? 0 : _number;
let style;
let currency;
switch (formatType) {
case 'currency':
style = 'currency';
currency = 'CNY';
break;
case 'percent':
style = 'percent';
break;
case 'quantity':
style = 'decimal';
break;
default:
throw new Error('Invalid formatType. Supported values are "currency", "percent", and "quantity".');
}
const options = {
style,
currency,
minimumFractionDigits: fractionDigits,
maximumFractionDigits: fractionDigits,
};
const numberFormat = new Intl.NumberFormat('zh-CN', options);
return numberFormat.format(number);
};
// Examples
/**
*
* @param number
* @param fractionDigits
* @returns
*/
export const formatCurrency = (number: number, fractionDigits: number) =>
format(number, fractionDigits, FormatType.currency); // ¥10,000.00
/**
*
* @param number
* @param fractionDigits
* @returns
*/
export const formatPercent = (number: number, fractionDigits: number) =>
format(number, fractionDigits, FormatType.percent); // 75.00%
/**
*
* @param number
* @param fractionDigits
* @returns
*/
export const formatQuantity = (number: number, fractionDigits = 2) =>
format(number, fractionDigits, FormatType.quantity); // 12,345.679
export default format;
/**
*
* @param num
* @returns
*/
function _isDecimal(num: number): boolean {
return Number.isFinite(num) && !Number.isInteger(num);
}