Javascript – Round a number to certain significant figures

I found an elegant solution written by Ateş Göral about rounding number to a certain significant figures in Javascript.

Magnetiq – Rounding to a Certain Significant Figures in JavaScript

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

alert(sigFigs(1234567, 3)); // Gives 1230000
alert(sigFigs(0.06805, 3)); // Gives 0.0681
alert(sigFigs(5, 3));       // Gives 5

 

Done =)

Advertisement

One thought on “Javascript – Round a number to certain significant figures”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.