JavaScript: Round a number to 2 decimal places.

This is a short guide on how to round a number to 2 decimal places using JavaScript. In the example below, I also will provide a JavaScript alternative to PHP’s number_format function.

Take a look at the custom JavaScript function below:

/**
 * Custom JavaScript function that rounds a number w/
 * decimal places.
 *
 * @param val - The value that you want to format with decimal places.
 * @param decimals - The number of decimal places that should be used.
 * @returns {float}
 */
function number_format(val, decimals){
    //Parse the value as a float value
    val = parseFloat(val);
    //Format the value w/ the specified number
    //of decimal places and return it.
    return val.toFixed(decimals);
}

I named this function number_format because that is the name of a popular PHP function that carries out a similar operation.

Our custom function takes in two parameters:

  • val: The number that we want to round.
  • decimals: The number of decimals that the number should be rounded to.

Inside our function, we parsed the val variable as a float by using JavaScript’s parseFloat function. We did this so that our function can also handle string variables. If you fail to parse a string variable before using the toFixed() method, your code will throw the following Uncaught TypeError:

Uncaught TypeError: val.toFixed is not a function

This is because the Number.prototype.toFixed() method can only be used with Number variables such as floats and integers.

Note that unlike PHP’s number_format function, this function does not add thousand separators.

You can test this function out by using the following examples:

console.log(number_format(2.333, 2)); //Result: 2.33
console.log(number_format("9.01345", 2)); //Result: 9.01
console.log(number_format(5, 2)); //Result: 5.00
console.log(number_format("383.48910093", 4)); //Result: 383.4891
console.log(number_format(33.92039, 1)); //Result: 33.9

As you can see, this function can handle both numbers and strings:

  • We were able to round the float 2.333 to 2 decimal places.
  • The string “9.01345” was rounded to 9.01.
  • An integer such as 5 will become “5.00”, with two zeros being appended behind the decimal place.
  • For “383.48910093”, we changed the second parameter to 4. This rounded the number to 4 decimal places, resulting in 383.4891.
  • Finally, we rounded 33.92039 to 1 decimal place, resulting in 33.9.

Hopefully, you found the code above useful!