Significant figures with nearest integer rounding

Online demo for https://gist.github.com/atesgoral/989140

by atesgoral

HTML

<pre id="out"></pre>

JavaScript

const sigFigs = (n,s,p)=>{with(Math)return p=s-floor(log(abs(n))/LN10)-1,s=pow(10,p),(round(n*s)/s).toFixed(p<0?0:p)};

document.getElementById('out').innerHTML = [
  sigFigs(1234567, 3),
  sigFigs(0.06805, 3),
  sigFigs(5, 3),
  sigFigs(1.3, 2),
  sigFigs(-1.3, 2),
  sigFigs(-134, 2),
  sigFigs(-135, 2),
  sigFigs(-136, 2)
].join('\n');