Currently, I have BigDecimal values with 3 decimal places shown in a JTable. When i get values as 2.500 or 1.000, I want to have 2.5 and 1.0 instead. That's why I tried this:
BigDecimal value;
BigDecimal value3 = new BigDecimal((String)model.getValueAt(e.getLastRow(), 1)).setScale(3, BigDecimal.ROUND_HALF_UP);
BigDecimal value2 = new BigDecimal((String)model.getValueAt(e.getLastRow(), 1)).setScale(2, BigDecimal.ROUND_HALF_UP);
if(valor3.equals(value2))
{
BigDecimal value1 = new BigDecimal((String)model.getValueAt(e.getLastRow(), 1)).setScale(1, BigDecimal.ROUND_HALF_UP);
if(value3.equals(value1))
value = valuer1;
else
value = value2;
}
else
value = value3;
But it doesn't work. It looks like '2.500'.equals('2.5') were false.
I also tried to give format to the JTable at its renderer:
class paramRenderer extends DefaultTableCellRenderer
{
private final DecimalFormat formatter = new DecimalFormat( "#.000" );
public void setValue() {
formatter.setMinimumFractionDigits(1);
formatter.setMaximumFractionDigits(3);
}
}
But it makes no difference at all.
Any other idea?
EDIT: Finaly I found over the Internet a solution:
BigDecimal trim(BigDecimal n)
{
try
{
while (true)
{
n = n.setScale(n.scale()-1);
}
}
catch (ArithmeticException e)
{
// Not "real" error: No more trailing zeroes -> Just exit // setScale() tries to eliminate a non-zero digit -> Out of the loop // Remember exceptions are not recommended for exiting loops, but this seems to be the best way...
}
return n;
}
And works great! Thank you very much for the help anyway :)