2

I am trying to add row values of datatype(money) in which zeros after decimal are automatically formed in Jtable like these 55.0000 28.0000 60.0000 20.0000 50.0000

on runtime log showing this error

java.math.BigDecimal cannot be cast to java.lang.String

Here is the code for rows addition from Jtable

        double total = 0;
        for(int i = 0; i<table.getRowCount(); i++){
            double amount = Double.parseDouble((String) table.getValueAt(1, 6) );
            total+=amount;
        }
        totalSum.setText(String.valueOf(total));

*

Is there any way to add float type values??

    *
4
  • 1
    table.getValueAt(1, 6) already returns a BigDecimal, why do you think you need to cast it to String? What's wrong with using BigDecimal.doubleValue()? Commented Aug 15, 2017 at 4:50
  • You can reliably convert objects to strings using object.toString() (assuming object isn't null). Commented Aug 15, 2017 at 4:51
  • Jim Garrison, sir can you please give me a precise solution. Commented Aug 15, 2017 at 4:53
  • 1
    and, BTW, you're always getting the value of the same cell (1,6). I guess you meant table.getValueAt(i, 6) Commented Aug 15, 2017 at 5:22

2 Answers 2

3

Try something like this:

BigDecimal total = BigDecimal.ZERO;
for (int i = 0; i < table.getRowCount(); ++i) {
    final BigDecimal amount = (BigDecimal)table.getValueAt(i, 6);
    total = total.add(amount);
}
totalSum.setText(total.toString());
Sign up to request clarification or add additional context in comments.

Comments

3

Change

double amount = Double.parseDouble((String) table.getValueAt(1, 6) );

to

double amount = table.getValueAt(1, 6).doubleValue();

There's no need to convert a BigDecimal to String just to make a double.

2 Comments

@KamranAshiq All the compiler knows is that getValueAt() is an Object. Apparently the method is defined with Object as the return type. If the method will really return a BigDecimal in this case you can cast it to a BigDecimal and then use doubleValue(): ((BigDecimal)table.getValueAt(1,6)).doubleValue(). This only works if the object it returns really is a BigDecimal. It won't convert anything else to a BigDecimal. Instead, you'll get an exception if it's not the right type.
Yes, but I think you should point out this loses precision: you can do it only with BigDecimal, and not have this issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.