I am having a rounding issue when using BigDecimal. When i try to round a number to one decimal place, i.e. 3.65 to be rounded to one decimal place, I get the result as 3.6 and not 3.7 ... Any ideas?
This is my code:
public
String formatData(double value, int decimalPlaces) {
try {
java.math.BigDecimal bd = new java.math.BigDecimal(value);
value = bd.setScale(decimalPlaces, java.math.BigDecimal.ROUND_HALF_UP).doubleValue();
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
String num = nf.format(value);
int decimalIndex = num.indexOf(".");
int addDecimal = num.length() - decimalIndex;
if(decimalIndex == -1 ) {
num = num.concat(".");
for(int i = 0; i < decimalPlaces; i++)
num = num.concat("0");
}
else if(addDecimal <= decimalPlaces) {
for( int i = addDecimal; i <= decimalPlaces; i++)
num = num.concat("0");
}
return (num);
} catch (java.lang.Exception ge) {}
return ("");
}