Tuesday, May 8, 2012

Code weirdness

I recently came across very strange behaviour in the tertiary operator:

<boolean-expression> ? <statement> : <statement>;

See if you can spot it. The idea is as follows. If the number is a round number (i.e. 4.0 or 8.0) then the number should be displayed without the trailing .0. However, if it is not, the fractional part should display. Here's the test class containing three tests... Which test(s) fails and why?
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.hamcrest.Matchers.equalTo;
public class TestNumberFormatting {
@Test
public void testDetectRoundNumber() {
double number = 2.2;
assertFalse((int) Math.round(number) == number);
number = 2;
assertTrue((int) Math.round(number) == number);
}
@Test
public void testWeirdnessTakeOne() {
double number = 3.1415;
boolean isRoundNumber = (int) Math.round(number) == number;
assertFalse(isRoundNumber);
String formattedString = String.valueOf(isRoundNumber ? (int) number : number);
assertThat(formattedString, equalTo("3.1415"));
}
@Test
public void testWeirdnessTakeTwo() {
double number = 2.0;
boolean isRoundNumber = (int) Math.round(number) == number;
assertTrue(isRoundNumber);
String formattedString = String.valueOf(isRoundNumber ? (int) number : number);
assertThat(formattedString, equalTo("2"));
}
}