面试题答案
一键面试function financialCalculation(amount1: bigint, amount2: bigint, operator: '+' | '-' | '*' | '/'): bigint {
switch (operator) {
case '+':
return amount1 + amount2;
case '-':
return amount1 - amount2;
case '*':
return amount1 * amount2;
case '/':
return amount1 / amount2;
default:
throw new Error('Unsupported operator');
}
}
使用bigint
类型比使用普通Number
类型更合适的原因:
- 精度问题:
Number
类型在JavaScript中是双精度浮点数,能够精确表示的整数范围有限(-2^53 + 1 到 2^53 - 1)。对于金融应用中的大金额,很容易超出这个范围导致精度丢失。而bigint
类型可以表示任意精度的整数,确保金额计算的准确性。 - 金融场景需求:在金融领域,金额的准确性至关重要,哪怕是微小的精度误差都可能导致严重的财务问题。
bigint
提供的精确计算特性正好满足这一需求。