1

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 :)

Bhushan
  • 18,329
  • 31
  • 104
  • 137
Roman Rdgz
  • 12,836
  • 41
  • 131
  • 207

3 Answers3

0

Try this format #.0## for the formatter

denis.solonenko
  • 11,645
  • 2
  • 28
  • 23
  • It doesn't work. I'm updating the JTable values with TableModel.setValueAt(float value, int row, int column), while I'm extending the setValue method at the renderer... I know I'm doing wrong, but where shall I fix this? – Roman Rdgz Jul 11 '11 at 11:22
0
  • the first comparison is false, because you have different scales - value2 has 2 and value3 has 3. If you make them the same, it works
  • you don't need BigDecimal if you only want to display things. The decimal format should work, but you should also set the maximum fraction digits to 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

Try to do like this,

DecimalFormat df = new DecimalFormat("#.#");
df.format(2.500);   // returns 2.5
df.format(1.000);   // returns 1.0
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164