3 ms·
i recently worked around a ">=" bug in javascript javascript only uses floating point numbers and this is a common complaint when discussing the language.. if
by justifier 12y ago
i recently worked around a ">=" bug in javascript
javascript only uses floating point numbers and this is a common complaint when discussing the language.. if you have ever wondered why, here is an example:
var n={}
var e={}
n.ndiv = document.getElementById("nid")
e.ediv = document.getElementById("eid")
transform(n)
transform(e)
if ( n.x >= e.x){
//imagine
}
here we have two divs: n and e; that undergo transformations in the DOM through a function: transform(); then their respective x value in the window is compared
the problem is that when running tests divs with equal initial configurations my expected outcomes would fail
when i looked into it it turned out to be a floating point issue where "equal" values would fail because 'e' would be slightly greater than 'n'
i had to implement my own gtoreq() and oreqto() functions to check is check if equal within a margin of error:
gtoreq(n,e){
if ( oreqto(n,e) ){
return true
} else {
if ( n > e ) {
return true
} else {
return false
}
}
oreqto(n,e){
var allowederror = .517 //slightly more than .5
if ( Math.abs(n-e)) < allowederror ) {
return true
} else {
return false
}
}
for whatever reason the error was always .5, more evidence pinpointing the error as a javascript floating point issue
- bmm6o 12y ago> var allowederror = .517 //slightly more than .5 You should probably explain your mystery value better than that.