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.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to test if a number is a power of 2.
Next: Write a JavaScript function to check whether a value is an integer or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-math-exercise-14.php