javascriptroundingsignificant-digits

How can I round to an arbitrary number of significant digits with JavaScript?


I tried below sample code

function sigFigs(n, sig) {
    if ( n === 0 )
        return 0
    var mult = Math.pow(10,
        sig - Math.floor(Math.log(n < 0 ? -n: n) / Math.LN10) - 1);
    return Math.round(n * mult) / mult;
 }

But this function is not working for inputs like sigFigs(24730790,3) returns 24699999.999999996 and sigFigs(4.7152e-26,3) returns: 4.7200000000000004e-26

If anybody has working example please share. Thanks.


Solution

  • You can try javascript inbuilt method-

    Number( my_number.toPrecision(3) )
    

    For Your case try

    Number( 24730790.0.toPrecision(5) )
    

    For your refrence and working example you can see link