Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 310
suresh inakollu Avatar asked Apr 02 '16 04:04

suresh inakollu


People also ask

Why does Javascript have rounding errors?

This post doesn't get into the details of floating-point arithmetic, but the short of it is most programming languages use a binary floating-point representation which can only approximate many decimal fractions. This results in rounding errors for the most common approaches to rounding in JavaScript.

How do you round to the number of significant figures?

It rounds to the most important figure in the number. To round to a significant figure: look at the first non-zero digit if rounding to one significant figure. look at the digit after the first non-zero digit if rounding to two significant figures.

How do you round off digits in Javascript?

The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).

How do you set precision in Javascript?

The toPrecision() method in Javascript is used to format a number to a specific precision or length. If the formatted number requires more digits than the original number then decimals and nulls are also added to create the specified length.


1 Answers

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

like image 58
D Mishra Avatar answered Sep 29 '22 22:09

D Mishra