1

I would like to round a number to 2 leading digits, using pure JavaScript. I want to give a rough idea of the number and its size, but I don't want to bother the listener with too many digits.

So 6832 should round to 6800, but 8773278475 should round to 8800000000, not 8773278400.

2 Answers 2

3

This function gives me the right results for integers:

/**
 * @param {integer} num - The number to round
 * @param {integer} leadingDigits - How many significant digits at the start to keep
 * @returns {integer} rounded num
 */
function round(num, leadingDigits) {
  let precision = Math.pow(10, num.toString().length - leadingDigits);
  return Math.round(num / precision) * precision;
}

console.log(round(6832, 2));
console.log(round(8773278475, 2));
console.log(round(8, 2));

This returns, as expected:

6800
8800000000
8

But it fails for float, due to the .toString().length hack. If somebody has a better solution, please feel free to post it.

A good solution is short and easy to understand.

Sign up to request clarification or add additional context in comments.

Comments

1

The rarely used built-in JS function .toExponential() converts a number into string exponential notation (example: "5.6e+2"). The function handles rounding to the precision specified, so all you have to do is convert the string back to a number.

const round = (num, leadingDigits) =>
   // Rounds a number to the specified digits of precision.
   // Example: round(555.55, 2) -> "5.6e+2" -> 560
   Number(num.toExponential(leadingDigits - 1));

Sample usage:

console.log(round(333.333, 1));      //output: 300
console.log(round(333.333, 2));      //output: 330
console.log(round(333.333, 3));      //output: 333

console.log(round(555.555, 1));      //output: 600
console.log(round(555.555, 2));      //output: 560
console.log(round(555.555, 3));      //output: 556

console.log(round(999.999, 1));      //output: 1000
console.log(round(999.999, 2));      //output: 1000
console.log(round(999.999, 3));      //output: 1000

console.log(round(-0.00222222, 1));  //output: -0.002
console.log(round(-0.00222222, 2));  //output: -0.0022
console.log(round(-0.00222222, 3));  //output: -0.00222

console.log(round(6832, 2));         //output: 6800
console.log(round(8773278475, 2));   //output: 8800000000
console.log(round(8, 2));            //output: 8

Fake precision is a huge nuisance, and a lot of web applications could be improved by cleaning up useless and even misleading digits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.