mofang-mopai-utils
Version:
Use it in Mopai system
86 lines (84 loc) • 3.38 kB
text/typescript
// 定义一个执行数学运算的函数,接收两个数字 a 和 b,以及一个操作符 method,返回运算结果
const execMath = (a: number = 0, b: number = 0, method: string): number => {
// 定义一个数组,包含所有支持的操作符
const validMethods = ['+', '-', '*', '/'];
// 检查传入的操作符是否合法
if (!validMethods.includes(method)) {
// 若操作符不合法,输出错误信息
console.error(`不支持的操作符: ${method}`);
// 返回 0
return 0;
}
// 检查是否为除法操作且除数为零
if (method === '/' && b === 0) {
// 若除数为零,输出错误信息
console.error('除数不能为零');
// 返回 0
return 0;
}
// 计算 a 和 b 中小数点后的最大位数
const decimalLength = Math.max(getDecimalLength(a), getDecimalLength(b));
// 将 a 转换为整数,补全小数点后的位数
const x = transformToInteger(a, decimalLength); // 补位后的a值
// 将 b 转换为整数,补全小数点后的位数
const y = transformToInteger(b, decimalLength); // 补位后的b值
// 计算补位的基数,用于后续的除法运算
const z = Math.pow(10, decimalLength); // 补位数
// 根据操作符执行相应的数学运算
switch (method) {
// 加法操作
case '+':
// 返回加法运算结果
return (x + y) / z;
// 减法操作
case '-':
// 返回减法运算结果
return (x - y) / z;
// 乘法操作
case '*':
// 返回乘法运算结果
return (x * y) / (z * z);
// 除法操作
case '/':
// 返回除法运算结果
return (x / y) * z;
// 默认情况,处理不合法的操作符
default:
// 返回 0
return 0;
}
}
// 计算一个数字或字符串表示的数字的小数点后的位数
const getDecimalLength = (num: number | string): number => {
// 若传入的是字符串,尝试将其转换为数字
if (typeof num === 'string') {
try {
// 将字符串转换为浮点数
num = parseFloat(num);
} catch (error) {
// 若转换失败,输出错误信息
console.error(`无法将字符串转换为数字: ${num}`);
// 返回 0
return 0;
}
}
// 将数字转换为字符串
const numStr = num.toString();
// 查找小数点的位置
const decimalIndex = numStr.indexOf('.');
// 若不存在小数点,返回 0;否则返回小数点后的位数
return decimalIndex === -1 ? 0 : numStr.length - decimalIndex - 1;
}
// 将一个数字转换为整数,补全指定的小数位数
const transformToInteger = (num: number, offset: number): number => {
// 将数字转换为字符串
const numStr = num.toString();
// 分割整数部分和小数部分
const [integerPart, decimalPart = ''] = numStr.split('.');
// 补全小数部分的位数
const paddedDecimal = decimalPart.padEnd(offset, '0');
// 将整数部分和补全后的小数部分拼接,并转换为整数
return parseInt(integerPart + paddedDecimal, 10);
}
// 导出 execMath 函数作为默认导出
export default execMath