javascript – how to prevent toFixed from rounding off decimal numbers

That’s even simpler:

function truncateToDecimals(num, dec = 2) {
  const calcDec = Math.pow(10, dec);
  return Math.trunc(num * calcDec) / calcDec;
}

So:

truncateToDecimals(123456.786) -> 123456.78

Leave a Comment