I need to compare two float values to a certain precision (that is 4 decimal places):
var float1 = 0.0025132741228718345;
var float2 = 0.0025132812393818293;
The two options I see:
Math.floor(float1 * 10000) === Math.floor(float2 * 10000); // 25 === 25
...or:
float1.toFixed(4) === float2.toFixed(4) // "0.0025" === "0.0025"
Since operation will happen 60 times a second and I was asking myself:
function floor(f1, f2) {
return Math.floor(f1 * 10000) === Math.floor(f2 * 10000);
}
function toFixed(f1, f2) {
return f1.toFixed(4) === f2.toFixed(4);
}
function subtract(f1, f2) {
return Math.abs(f1 - f2) < 0.00001;
}
function test(fn) {
console.time(fn.name);
for (let i = 0; i < 1000000; ++i) {
fn(Math.random(), Math.random());
}
console.timeEnd(fn.name);
}
for (const fn of [floor, toFixed, subtract]) {
test(fn);
}
Between the two options that you gave, The Math.floor
approach is the faster one.
Might be a wise choice to go for subtract
, though.
(Run this benchmark yourself if you don't believe me.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With