Javascript Round Numbers – ZEN Solution

A useful javascript function for rounding numbers to a certain precision:

function f_Round(x, n=0) {
  let tempx = x*10;
  tempx = tempx.toFixed(n) / 10;
  return +tempx.toFixed(n);
}

and one-line function

function f_Round(x, n=0) {
  return +((x*10).toFixed(n) / 10).toFixed(n);
}

Round alternative for more precission, useful for larger numbers:

function f_Round(x, n=0) {
  let decimal = x.toString(10).split(".");
  if (decimal.length != 2)
    return +(x + '.00');

  let nsplit = decimal[1] / Math.pow(10,n+1);
  let fractional = Number.parseFloat(nsplit).toPrecision(n) * Math.pow(10,n);
  return +(decimal[0] + '.' + fractional);
}

 

byrev Written by:

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *