开发者

Problem converting String->Float->String

I have a JTable where i enter some values. This is the listener function to know if it has been made any change at the values, so i can update them. Values must have 开发者_开发问答the format indicated (#.###), so I'm doing this fix to round the float to 3 decimal places if the client enter more than 3.

    private class CambioTablaPretratamientoListener implements TableModelListener{
    public void tableChanged(TableModelEvent e){
        try{
            if(enviarDatosADispositivo){
                TableModel model = (TableModel)e.getSource();
                float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));
                DecimalFormat dec = new DecimalFormat("#.###");
                String aux = dec.format(value);
                if(model.getValueAt(e.getLastRow(), 1).equals(aux))
                    return;
                else
                    model.setValueAt(aux, e.getLastRow(), 1);
                value = Float.parseFloat(aux);

                String nombreAtributo = (String)model.getValueAt(e.getLastRow(), 0);

                nodoAModificar.setPretratamientUserParameter(nombreAtributo, value);     
            }
        }catch(BusinessException ex){
            ex.printStackTrace();
        }
    }
}

Code seems to work at first, because it rounds and the number appears in the table, but the value is not getting updated. I guess I'm doing something wrong with the DecimalFormat, because if I leave the function like this one, it works:

    private class CambioTablaPretratamientoListener implements TableModelListener{
    public void tableChanged(TableModelEvent e){
        try{
            if(enviarDatosADispositivo){
                TableModel model = (TableModel)e.getSource();
                float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));
                String nombreAtributo = (String)model.getValueAt(e.getLastRow(), 0);

                nodoAModificar.setPretratamientUserParameter(nombreAtributo, value);     
            }
        }catch(BusinessException ex){
            ex.printStackTrace();
        }
    }
}

And finall


You seem to think that converting a floating-point number to a String and back again can cause it to have a definite number of decimal places. This is fallacious. FP values don't have any decimal places. They have binary places. These only correspond to fixed numbers of decimal places if the fractional part is a negative power of 2, e.g. 0.5, 0.125, 0.0625, etc.


Instead, apply your DecimalFormat as a custom table cell renderer.


If you use BigDecimal, you could actually truncate the numbers, instead of trying to use Float's (lack of) precision.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜