代碼:
const math_helper = {}; /* 加法 */ math_helper.add = function(num1, num2) { // 兩個參數應爲有效的數字 if (typeof num1 !== 'number' || typeof num2 !== 'number') { throw new Error('非法的加數!'); } // 如果兩個數字中有一個爲整數 if (Number.isInteger(num1) || Number.isInteger(num2)) { return num1 + num2; } // 如果都爲小數 const formattedNum1 = String(num1).split('.'); const formattedNum2 = String(num2).split('.'); const zeroSize = Math.max(formattedNum1[1].length, formattedNum2[1].length); const divi = '1'.padEnd(zeroSize + 1, '0'); return (num1 * divi + num2 * divi) / divi; };
* 浮點數轉整數