Java:转换数据类型

时间:2011-06-21 08:55:03

标签: java

我正在使用JTable,其单元格数据包含在Object中。一列显示float个数字。我想将值加到float,将小数位数限制为3,然后我想在单元格中重新加载正确的数据,所以我想再次将值设置到单元格中。问题出现在上次转换中:

 private class CambioTablaMeasurementListener implements TableModelListener{

    public void tableChanged(TableModelEvent e){
        try{
            if(sendDataToDisp){
                TableModel model = (TableModel)e.getSource();
                float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));
               // Now i want to limit to only 3 decimal places, so:

                double aux = Math.round(value*1000.0)/1000.0;
                value = (float) aux;
                Float F = new Float(value);

                // Now i want to load data back to the cell, so if you enter 0.55555, the cell shows 0.555. This Line gives me an exception (java.lang.Float cannot be cast to java.lang.String):
                model.setValueAt(F, e.getLastRow(), 1);

                // Here I'm getting another column, no problem here:
                String nombreAtributo = (String)model.getValueAt(e.getLastRow(), 0);
                nodoAModificar.setCommonUserParameter(nombreAtributo, value);

            }
           ...}

2 个答案:

答案 0 :(得分:2)

您需要将Float个实例转换为String

model.setValueAt(F.toString(), e.getLastRow(), 1);

model.setValueAt(String.valueOf(F), e.getLastRow(), 1); // preferred since it performs null check

答案 1 :(得分:2)

您可以使用DecimalFormat以给定格式将float显示为String:

...
float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));             
DecimalFormat dec = new DecimalFormat("#.###");
model.setValueAt(dec.format(value), e.getLastRow(), 1);
...