javaScript四舍五入方法

function roundNumber(number, decimalPlaces) {
    if (typeof number !== 'number' || typeof decimalPlaces !== 'number') {
        throw new Error('Both arguments must be numbers');
    }

    const factor = Math.pow(10, decimalPlaces);
    return Math.round(number * factor) / factor;
}

// 示例
const originalNumber = 3.14159;
const roundedNumber = roundNumber(originalNumber, 2);
console.log(roundedNumber);  // 输出: 3.14

posted on 2023-12-26 15:35  柴头人仔  阅读(7)  评论(0编辑  收藏  举报