1234567891011121314151617181920212223242526272829303132333435363738394041 |
- // 加法
- function add(a, b) {
- const precision = Math.max(getPrecision(a), getPrecision(b));
- const multiplier = Math.pow(10, precision);
- return (multiply(a, multiplier) + multiply(b, multiplier)) / multiplier;
- }
- // 减法
- function subtract(a, b) {
- const precision = Math.max(getPrecision(a), getPrecision(b));
- const multiplier = Math.pow(10, precision);
- return (multiply(a, multiplier) - multiply(b, multiplier)) / multiplier;
- }
- // 乘法
- function multiply(a, b) {
- const precision = getPrecision(a) + getPrecision(b);
- const multiplier = Math.pow(10, precision);
- return Math.round(a * multiplier * b) / multiplier;
- }
- // 除法
- function divide(a, b) {
- const precision = Math.max(getPrecision(b), getPrecision(a));
- const divisor = Math.pow(10, precision);
- return (a * divisor) / (b * divisor);
- }
- // 获取浮点数的精度
- function getPrecision(num) {
- const str = num.toString();
- const decimalIndex = str.indexOf('.');
- return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1;
- }
- export {
- add,
- subtract,
- multiply,
- divide
- }
|