settingsAccountsettings
Menusettings

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.

Examples:

Input:
[3.1415926535897932384626433832795, 2]

Output:
3.14


Input:
[10.5, 3]

Output:
10.5

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