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.
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!