w3resource

JavaScript: Round a number to a given specific decimal places

JavaScript Math: Exercise-14 with Solution

Round Number to Decimal Place

Write a JavaScript function to round a number to decimal place.

Test Data:
console.log(precise_round(12.375,2));
console.log(precise_round(12.37499,2));
console.log(precise_round(-10.3079499, 3));
Output :
"12.38"
"12.37"
"-10.308"

Visual Presentation:

JavaScript: Math - Round a number to a given specific decimal places.

Sample Solution:

JavaScript Code:

// Reference: https://bit.ly/3zxAhnH
// Define a function named precise_round that rounds a number to a specified precision.
function precise_round(n, r) {
    // Convert the floor of n to a string.
    let int = Math.floor(n).toString();
    // Check if n or r are not numbers, if so, return 'Not a Number'.
    if (typeof n !== 'number' || typeof r !== 'number') return 'Not a Number';
    // Remove leading '+' or '-' from the integer part of n.
    if (int[0] == '-' || int[0] == '+') int = int.slice(int[1], int.length);
    // Round n to the specified precision using toPrecision method.
    return n.toPrecision(int.length + r);
}

// Output the result of rounding 12.375 to 2 decimal places to the console.
console.log(precise_round(12.375, 2));
// Output the result of rounding -10.3079499 to 3 decimal places to the console.
console.log(precise_round(-10.3079499, 3));
// Output the result of rounding 10.49999 to 0 decimal places to the console.
console.log(precise_round(10.49999, 0));
// Output the result of rounding 10.49999 to 2 decimal places to the console.
console.log(precise_round(10.49999, 2));

Output:

12.38
-10.308
10
10.50

Flowchart:

Flowchart: JavaScript Math- Round a number to a given specific decimal places

Live Demo :

See the Pen javascript-math-exercise-14 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that rounds a number to a specified number of decimal places using arithmetic operations.
  • Write a JavaScript function that rounds a number and returns the result as a number, not a string.
  • Write a JavaScript function that implements banker's rounding (round half to even) to a given decimal place.
  • Write a JavaScript function that handles rounding for both positive and negative numbers to a fixed number of decimals.

Go to:


PREV : Check Power of 2.
NEXT : Check If Value is Integer.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.