Skip to content

Instantly share code, notes, and snippets.

@aeinbu
Created May 3, 2021 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeinbu/4af7d1b8c74acddb8278ff23b839a3fc to your computer and use it in GitHub Desktop.
Save aeinbu/4af7d1b8c74acddb8278ff23b839a3fc to your computer and use it in GitHub Desktop.
function round(value, precision) {
return Number(Math.round(value + "e" + precision) + "e-" + precision)
}
function strictCompare(left, right) {
console.log(`strictCompare(${left}, ${right})`);
return left === right;
}
function badRelaxedCompare(left, right) {
left = round(left, 9);
right = round(right, 9);
console.log(`badRelaxedCompare(${left}, ${right})`);
return left === right;
}
function goodRelaxedCompare(left, right) {
left = left.toPrecision(16);
right = right.toPrecision(16);
console.log(`goodRelaxedCompare(${left}, ${right})`);
return left === right;
}
//var a = 0.3 - 0.1;
//var b = 0.2;
//var a = 100.3 + 100.1;
//var b = 200.4;
var a = 1000000000.2 + 1000000000.1;
var b = 2000000000.3;
console.log(`a: ${a}, b: ${b}`);
console.log(strictCompare(a, b));
console.log(badRelaxedCompare(a, b));
console.log(goodRelaxedCompare(a, b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment