How to check for approximate numbers | Vanilla JS

Barbara Bombachini
Code Snippets
Published in
1 min readMar 19, 2018

Not overly complicated, but not so obvious…

Of course, you need to be comparing integers and you need to have a range in which the comparison would make sense.

Here’s a code snippet to simply subtract the numbers you’re trying to compare and evaluate if this difference is between the “range”.

var diff = Math.abs( a - b );

if( diff > 50 ) {
console.log('diff greater than 50');
}

Only 3 lines, and there’s happiness!

--

--