Funny bug in Java

import java.math.*;

public class Test{

public static void main(String args[]){

Double a = new Double(0.865);

System.out.println("The Rounded price a is "+roundOff1(a));

}

public static Double roundOff1(Double finalDiscountedPrice){

BigDecimal roundfinalDiscPrice =

new BigDecimal(finalDiscountedPrice.doubleValue()).setScale(2,BigDecimal.ROUND_HALF_UP);

Double finalDiscPrice= new Double(roundfinalDiscPrice.doubleValue());

return finalDiscPrice;

}

}

I was trying to roundOff to a scale of 2. Ideal the above code should convert .865 to .87 but it doesnot.

it does convert for most of the number but for some it doesnt like .725 and .825. It will leave them as .72 and .83. But .625 and .925 will be converted to .63 and .93

Can any bdy suggest me what could be the problem or any other API to so this.

Thanks

[912 byte] By [me_gautam] at [2007-9-30 20:34:10]
# 1

Create the BigDecimal by using a string value instead of a double. There are probably trailing decimals in the double that are impacting the rounding.

In general you're better off creating BigDecimals from string values. Doubles can be like this 12.000000053 because of the conversion to binary floating point, when you really wanted 12.000.

You could also multiply the double by the appropriate power of ten, then cast to an int or use a floor90 method, and then divide by the power of ten to clean off the extra decimals:

((int)(12.000000053 * 1000)) / 1000D = 12.000

ChuckBing at 2007-7-7 1:23:38 > top of Java-index,Administration Tools,Sun Connection...