JavaScript round

Here’s an easy to use JavaScript function to round a number to any decimal place.

JavaScript code

I posted two functions below. Both functions will round the number to a given decimal place but one will display trailing zeros (3.000) while the other one will not (3). Copy whichever function works best for your project and let me know if you have any questions by posting a comment.

Without trailing zeros

function roundNumber(num, dec){
    var decimal = Math.pow(10,dec);
    var number = Math.round(num*decimal)/decimal;
    return number;
}

roundNumber(12.44,0) //12
roundNumber(12.44,1) //12.4
roundNumber(12.44,3) //12.44 <-- won't display the extra 0

With trailing zeros

function roundNumber(num, dec){
    var decimal = Math.pow(10,dec);
    var number = Math.round(num*decimal)/decimal;
    var zeros;
    
    if(dec > 0){
        number = number.toString();
        number = number.split('.');
        if(number.length == 1){ 
            zeros = dec;
            number = number[0] + '.' + addZero('',zeros);
        }else{
             zeros = dec - number[1].length;
             if(zeros > 0){
                 number = number[0] + '.' + addZero(number[1],zeros);   
             }else{
                 number = number[0] + '.' + number[1];   
             }   
        }
    }
    return number;
}

function addZero(num, zero){
    for(var x = 0; x < zero; x++){
        num = num + '0';   
    }   
    return num;
}

roundNumber(12.44,0) //12
roundNumber(12.44,1) //12.4
roundNumber(12.44,3) //12.440