37 lines
1.2 KiB
TypeScript
37 lines
1.2 KiB
TypeScript
import { BadRequestException } from '@nestjs/common';
|
|
|
|
export const MONEY_UNITS_PER_YUAN = 10_000;
|
|
|
|
export function moneyToNumber(value: number | bigint | null | undefined) {
|
|
if (value === null || value === undefined) return 0;
|
|
const result = typeof value === 'bigint' ? Number(value) : value;
|
|
if (!Number.isSafeInteger(result)) {
|
|
throw new RangeError('金额超过 JavaScript 安全整数范围');
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export function moneyUnitsToYuan(value: number | bigint | null | undefined) {
|
|
return moneyToNumber(value) / MONEY_UNITS_PER_YUAN;
|
|
}
|
|
|
|
export function moneyUnitsToFixedYuan(value: number | bigint | null | undefined) {
|
|
return moneyUnitsToYuan(value).toFixed(4);
|
|
}
|
|
|
|
export function assertMoneyUnits(
|
|
value: number,
|
|
label: string,
|
|
options: { allowNegative?: boolean; allowZero?: boolean } = {},
|
|
) {
|
|
if (!Number.isSafeInteger(value)) {
|
|
throw new BadRequestException(`${label}最多支持人民币小数点后 4 位,且不能超过安全金额范围`);
|
|
}
|
|
if (!options.allowNegative && value < 0) {
|
|
throw new BadRequestException(`${label}不能为负数`);
|
|
}
|
|
if (options.allowZero === false && value === 0) {
|
|
throw new BadRequestException(`${label}不能为 0`);
|
|
}
|
|
}
|