Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - If statement A is equal to B plus or minus 2

I've got a problem that seems easy to solve, however I'm not sure on the syntax.

I need to have an if/else statement run, but I'm not sure on how to set the conditions correctly.

Bad code:

if (float_a = float_b or is within +-2 of it) {
    do this
}
else {
    do that
}

What's the simplest way of accomplishing this?

like image 951
Numpty Avatar asked Apr 22 '12 00:04

Numpty


2 Answers

You can use Math.abs:

if (Math.abs(float_a-float_b) <= 2) { ... }

This means "if the absolute difference between a and b is within 2...".

like image 129
Sergey Kalinichenko Avatar answered Oct 13 '22 00:10

Sergey Kalinichenko


if(Math.abs(float_a - float_b) <= 2) {
    //do this
}
else {
    //do that
}
like image 32
lynks Avatar answered Oct 12 '22 23:10

lynks