Round number with X decimals (toFixed VS Math.round) (v2)

Revision 2 of this benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
toFixed
const formatNumber = (x, fractionDigits) => {
  return Number(x.toFixed(fractionDigits ?? 3).replace(/\.?0*$/, ''))
}
ready
Math.round
const formatNumber = (x, fractionDigits) => {
  const powed = Math.pow(10, fractionDigits ?? 2)
  return Math.round(Number(String(x).replace(/,/gi, '.')) * powed) / powed
}
ready
Math.round without verif
const formatNumber = (x, fractionDigits) => {
  const powed = Math.pow(10, fractionDigits ?? 2)
  return Math.round(x * powed) / powed
}
ready
toFixed with verif
const formatNumber = (x, fractionDigits) => {
  return Number(Number(x).toFixed(fractionDigits ?? 3).replace(/\.?0*$/, ''))
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.