feat: add formatNumber

pull/117/head^2
xingyu4j 2025-05-27 15:31:06 +08:00
parent d46c17293c
commit 64cd606c87
3 changed files with 99 additions and 0 deletions

View File

@ -283,6 +283,22 @@ setupVbenVxeTable({
return cellValue.toFixed(digits);
},
});
vxeUI.formats.add('formatFraction', {
tableCellFormatMethod({ cellValue }) {
if (cellValue === null || cellValue === undefined) {
return '0.00';
}
if (isString(cellValue)) {
cellValue = Number.parseFloat(cellValue);
}
// 如果非 number则直接返回空串
if (Number.isNaN(cellValue)) {
return '0.00';
}
return `${(cellValue / 100).toFixed(2)}`;
},
});
},
useVbenForm,
});

View File

@ -0,0 +1,82 @@
/**
*
* @param num
*/
export function formatToFraction(num: number | string | undefined): string {
if (num === undefined) return '0.00';
const parsedNumber = typeof num === 'string' ? Number.parseFloat(num) : num;
return (parsedNumber / 100).toFixed(2);
}
/**
* 1.00
* 使
*
* @param num
*/
export function floatToFixed2(num: number | string | undefined): string {
let str = '0.00';
if (num === undefined) {
return str;
}
const f = formatToFraction(num);
const decimalPart = f.toString().split('.')[1];
const len = decimalPart ? decimalPart.length : 0;
switch (len) {
case 0: {
str = `${f.toString()}.00`;
break;
}
case 1: {
str = `${f.toString()}0`;
break;
}
case 2: {
str = f.toString();
break;
}
}
return str;
}
/**
*
* @param num
*/
export function convertToInteger(num: number | string | undefined): number {
if (num === undefined) return 0;
const parsedNumber = typeof num === 'string' ? Number.parseFloat(num) : num;
return Math.round(parsedNumber * 100);
}
/**
*
*/
export function yuanToFen(amount: number | string): number {
return convertToInteger(amount);
}
/**
*
*/
export function fenToYuan(price: number | string): string {
return formatToFraction(price);
}
/**
*
*
* @param value
* @param reference
*/
export function calculateRelativeRate(
value?: number,
reference?: number,
): number {
// 防止除0
if (!reference || reference === 0) return 0;
return Number.parseFloat(
((100 * ((value || 0) - reference)) / reference).toFixed(0),
);
}

View File

@ -1,6 +1,7 @@
export * from './constants';
export * from './dict';
export * from './download';
export * from './formatNumber';
export * from './formatTime';
export * from './formCreate';
export * from './rangePickerProps';