Test name | Executions per second |
---|---|
Simple rounding | 4198704.5 Ops/sec |
Rounding with epsilon and string conversion | 1579440.2 Ops/sec |
Rounding with "if" statemen | 1489148.9 Ops/sec |
function round2(num, places) {
return +(Math.round(num + "e+" + places) + "e-" + places);
}
function round3(num, places) {
if (places === 2) {
return Math.round( Math.round( num * 1000 ) / 10 ) / 100
} else {
const multiplier = Math.pow(10, places)
return Math.round(num * multiplier) / multiplier
}
}
function round4(num, places) {
+(num.toLocaleString(
'en',
{ maximumFractionDigits: places, useGrouping: false }
))
}
Math.round(12.345 * 100) / 100
round2(12.345, 2)
round3(12.345, 2)
round4(12.345, 2)