rounding to an arbitrary number of significant digits in javascript is not working

suresh inakollu picture suresh inakollu · Apr 2, 2016 · Viewed 9.5k times · Source

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.

Answer

D Mishra picture D Mishra · Apr 2, 2016

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