DecimalFormat not ceiling properly

960 views Asked by At

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

EDIT:Another test as requested by comment. Still does not work.

//junit.framework.ComparisonFailure: null
//Expected :0.01
//Actual :0.00

@Test
public void testStackOverflow() throws Exception
{
double amount = 0.0000006;
String formatted = decimalFormatter.format(amount);
Assert.assertEquals("Unexpected formatted number", "0.01", formatted);
}

I noticed that for it to work, a number greater than 0 must be within the range of the pattern. Is this a bug or am I missing something?

1

There are 1 answers

0
Evgeniy Dorofeev On

Looks like a bug. This code

    BigDecimal bd = new BigDecimal("0.0000001");
    bd = bd.setScale(2, RoundingMode.CEILING);
    System.out.println(bd);

produces correct result

0.01