Rounding Numbers in JavaScript

/**
 * @description Rounds a number to the specified decimal places
 * @param {number} num - The number to round
 * @param {number} decimals - Number of decimal places
 * @returns {number|boolean} - Rounded number or false if invalid
 */
function roundToDecimals(num, decimals) {
    if (typeof num !== "number" || typeof decimals !== "number") return false;
    
    let factor = Math.pow(10, decimals);
    return Math.round(num * factor) / factor;
}

console.log(roundToDecimals(3.14159, 2)); // 3.14
console.log(roundToDecimals(1.6789, 3)); // 1.679
console.log(roundToDecimals("test", 2)); // false


Leave a comment

Your email address will not be published. Required fields are marked *