Number preceision

Benchmark created on


Setup

const round = (num, places) => {
	const roundToPlaces = Math.pow(10, places);

	return Math.round(num * roundToPlaces) / roundToPlaces;
};

Test runner

Ready to run.

Testing in
TestOps/sec
toFixed(4)
const n = 0.1;
const r = Math.fround(n);

console.log(`What we have "${r}", what we want "${n}"`);

const start = performance.now();

for (let i = 0; i < 1e6; i++) {
	r.toFixed(4);
}

const end = performance.now();

console.log(`Using toFixed we get ${r.toFixed(4)}`);
console.log(`toFixed(4) one million took: ${end - start}ms`);
ready
Regex
const n = 0.1;
const r = Math.fround(n);
const s = r.toString();
const re = /([0-9]*)\.([0-9]*?)0000.*/

console.log(`What we have "${s}", what we want "${n}"`);

const start = performance.now();

for (let i = 0; i < 1e6; i++) {
	s.replace(re, '$1.$2');
}

const end = performance.now();

console.log(`Using regex we get ${s.replace(re, '$1.$2')}`);
console.log(`Regexing one million took: ${end - start}ms`);
ready
Custom round
const n = 0.1;
const r = Math.fround(n);

console.log(`What we have "${r}", what we want "${n}"`);

const start = performance.now();

for (let i = 0; i < 1e6; i++) {
	round(r, 4);
}

const end = performance.now();

console.log(`Using round we get ${round(r, 4)}`);
console.log(`round(r, 4) one million took: ${end - start}ms`);
ready

Revisions

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