Warning: session_start() [function.session-start]: open(/tmp/sess_h3shfslgghmf2hecn8fpfn6or7, O_RDWR) failed: Disk quota exceeded (122) in /home/vipozico/forum.tutorials7.com/qa-include/qa-app-users.php on line 143
Round numbers to specific precision in JavaScript
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Round numbers to specific precision in JavaScript

+2 votes

Write a JS function (program/code) that rounds numbers to specific precision.

The input comes as an array of two numbers:

  • The first value is the number to be rounded;
  • The second is the precision (significant decimal places)

If a precision is passed, that is more than 15 it should automatically be reduced to 15.


[3.1415926535897932384626433832795, 2]


[10.5, 3]


The output should be printed to the console. Do not print insignificant decimals.

asked in JavaScript category by user eiorgert

1 Answer

+1 vote

Here is the solution of rounding the numbers in JavaScript:

function round(arr) {
    let [num,precision]=arr;//if you know how many element are in the array - you can assign them this way
    if (precision > 15) {
        precision = 15;
    let denominator = Math.pow(10, precision);
    console.log(Math.round(num * denominator) / denominator);
    //or use this code: console.log(Number(num.toFixed(precision)));

round([10.5, 3]);


answered by user mitko