Search code examples
javascriptintegerrounding

How do I round a number to a number of significant leading digits in JavaScript?


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.


Solution

  • 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.