Tuesday, 27 August 2013

DecimalFormat not ceiling properly

DecimalFormat not ceiling properly

We are currently running some tests which involve ceiling numbers that
have two decimal places. In order to achieve this, we are using Java's
DecimalFormat.
However, the tests are getting strange results, particularly for the case
when we wish to ceil up a '0.00xxx' number.
The following is the instance of the DecimalFormatter that is being used
by the tests:
DecimalFormat decimalFormatter = new DecimalFormat("#########0.00");
decimalFormatter.setRoundingMode(RoundingMode.CEILING);
This test works as expected, that is, it was ceiled correctly:
//The below asserts as expected
@Test
public void testDecimalFormatterRoundingDownOneDecimalPlace3()
{
String formatted = decimalFormatter.format(234.6000000000001);
Assert.assertEquals("Unexpected formatted number", "234.61",
formatted);
}
However, this does not:
//junit.framework.ComparisonFailure: Unexpected formatted number
//Expected :0.01
//Actual :0.00
@Test
public void testSmallNumber()
{
double amount = 0.0000001;
String formatted = decimalFormatter.format(amount);
Assert.assertEquals("Unexpected formatted number", "0.01",
formatted);
}
Can you please explain why we are getting this behaviour. Thanks

No comments:

Post a Comment