java.math.BigDecimal 不能转换为 java.lang.String?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45686654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:50:20  来源:igfitidea点击:

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

javajtablesqldatatypes

提问by Kamran Ashiq

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

我正在尝试添加数据类型(金钱)的行值,其中在 Jtable 中自动形成小数点后的零,如下所示 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

java.math.BigDecimal 不能转换为 java.lang.String

Here is the code for rows addition from Jtable

这是 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??

有没有办法添加浮点类型值?

    *
    *

回答by Usagi Miyamoto

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());

回答by Jim Garrison

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 BigDecimalto Stringjust to make a double.

没有必要将 a 转换BigDecimalString只是为了制作 a double