Created
May 3, 2021 15:44
-
-
Save aeinbu/4af7d1b8c74acddb8278ff23b839a3fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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