2.000000001 == 2 // true
4.9999999998 >= 4.9999999999 // true
7.99 == 8.02 //false
// Так как 7.99 равен только 7.98, 7.99, 8.00
// А 8.02 == 8.01, 8.02, 8.03
const compare= (v, v2) => {
const parts = String(v).split('.')
const pow = parts.length > 1 ? parts.pop().length : 0
return Math.round(Math.abs(v - v2) * Math.pow(10, pow)) <= 1
}
console.log(compare(7.98, 7.99)) // true
console.log(compare(7.98, 7.97)) // true
console.log(compare(7.98, 8)) // false
console.log(compare(0.1, 0.15)) // true
const compare= (v, v2) => {
const parts = [v, v2].map(v => String(v).split('.'))
const pow = Math.max(...parts.map(v => v.length > 1 ? v.pop().length : 0))
return Math.round(Math.abs(v - v2) * Math.pow(10, pow)) <= 1
}
console.log(compare(7.98, 7.99)) // true
console.log(compare(7.98, 7.97)) // true
console.log(compare(7.98, 8)) // false
console.log(compare(0.1, 0.15)) // false
(123.4567).toExponential() // "1.234567e+2"
[1, 10)
, после запятой и степень.[1, 234567, 2]
>=
, <=
const fuzzy = {
split: n => {
const parts = n.toExponential().split('e')
.map((p, i) => i ? parseInt(p) : p.split('.').map(x => parseInt(x)));
if (parts[0].length < 2) parts[0].push(0);
return [parts[0][0], parts[0][1], parts[1]];
},
eq: (a, b) => {
a = fuzzy.split(a);
b = fuzzy.split(b);
if (a[2] !== b[2]) return false;
const diff = Math.abs(a[1] - b[1]);
if (diff === 0) return Math.abs(a[0] - b[0]) <= 1;
if (a[0][0] !== b[0][0]) return false;
return (diff <= 1);
}
}
fuzzy.eq( 12.1234, 12.1233) // true
const tests = [
[1, 1, true],
[111, 112, true],
[0.001, .002, true],
[0.001, .0025, false],
[0.001, .003, false],
[12.345, 1.2345, false],
[123.88, 123.870, true],
[-1.11111111, 1.11111110, false],
[-1.11111111, -1.11111112, true],
[2.000000001, 2, true],
[4.9999999998, 4.9999999999, true],
[7.9, 8.02, false],
[7.99, 7.98, true],
[7.99, 7.99, true],
[7.99, 8.00, true], // НЕ ПРОХОДИТ! Надо этот случай предусмотреть, но я ушёл спать.
];
let allok = true;
tests.forEach(test => {
if (fuzzy.eq(...test) !== test[2]) {
console.log("FAIL:", test);
allok = false;
} else {
console.log("OK:", test);
}
});
console.log(allok ? 'All OK!' : "Some tests FAILED");