w3resource

JavaScript: Round a number to a specified number of digits and strip extra zeros

JavaScript Math: Exercise-24 with Solution

Write a JavaScript function to round a number to a specified number of digits and strip extra zeros (if any).

Test Data :
var a = -4.55555;
console.log(result);
-4.5556
var a = 5.0001000;
console.log(result);
5.0001

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript function to round a number to a specified number of digitsand strip extra zeros (if any).</title>
</head>
<body>

</body>
</html>

JavaScript Code:

//var a = -1.1230000;
//var a = 0.0000009999999;
//var a = 1.000000000;
//var a = -4.55555;
//var a = 5.0001000;
var a = 1.1234000;

var result = parseFloat(a.toFixed(4));
console.log(result);

Sample Output:

1.1234

Pictorial Presentation:

JavaScript: Math - Round a number to a specified number of digits and strip extra zeros.

Live Demo:

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


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to create a UUID identifier.
Next: Write a JavaScript function to make currency math (add, subtract, multiply, division etc.).

What is the difficulty level of this exercise?



JavaScript: Tips of the Day

Errors

const name = 'Owen';

console.log(name());

The variable name holds the value of a string, which is not a function, thus cannot invoke.
TypeErrors get thrown when a value is not of the expected type. JavaScript expected name to be a function since we're trying to invoke it. It was a string however, so a TypeError gets thrown: name is not a function!
SyntaxErrors get thrown when you've written something that isn't valid JavaScript, for example when you've written the word return as retrun. ReferenceErrors get thrown when JavaScript isn't able to find a reference to a value that you're trying to access.

Ref: https://bit.ly/3jFRBje