JavaScript: Round a number to a specified number of digits and strip extra zeros
JavaScript Math: Exercise-24 with Solution
Round and Strip Extra Zeros
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:
JavaScript Code:
// Declare a variable named a and assign it a floating-point number value with trailing zeros.
// var a = -1.1230000;
// var a = 0.0000009999999;
// var a = 1.000000000;
// var a = -4.55555;
// var a = 5.0001000;
var a = 1.1234000;
// Round the value of 'a' to 4 decimal places and convert it to a floating-point number.
var result = parseFloat(a.toFixed(4));
// Output the result to the console.
console.log(result);
Output:
1.1234
Visual Presentation:
Live Demo:
See the Pen javascript-math-exercise-24 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 digits and removes trailing zeros using regex.
- Write a JavaScript function that formats a number to fixed decimals then strips redundant zeros, returning a clean numeric string.
- Write a JavaScript function that rounds a number and converts it to a string without unnecessary decimal points.
- Write a JavaScript function that handles both positive and negative numbers while rounding and stripping extra zeros.
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?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics