簡體   English   中英

NumberFormatException:對於輸入字符串:TextField中的“ XXX,XX”,與語言環境相關

[英]NumberFormatException: For input string: “XXX,XX” in TextField, related to locale

我有一個控制器類,可以加載相應選擇的場景。 我稱它為“ CMenu”。

/*** Other methods that load other menu entries ***/

/**
 * Menu de Usuarios
 * 
 * @param event
 * @throws Exception
 */
public void menuUsuarios(ActionEvent event) throws Exception {
    try {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Usuarios.fxml"));
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("/styles/application.css").toExternalForm());
        Stage stage = new Stage();
        stage.setTitle("Menu de usuarios");
        stage.setScene(scene);
        stage.setResizable(false);
        // Llamamos a la ventana de menu
        stage.show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * Menu de Inventario
 * 
 * @param event
 * @throws Exception
 */
public void menuProductos(ActionEvent event) throws Exception {
    try {
        Locale.setDefault(new Locale("es"));
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Productos.fxml"));
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("/styles/application.css").toExternalForm());
        Stage stage = new Stage();
        stage.setTitle("Menu de Productos");
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * Menu de Empleados
 * 
 * @param event
 * @throws Exception
 */
public void menuEmpleados(ActionEvent event) throws Exception {
    try {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Empleados.fxml"));
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("/styles/application.css").toExternalForm());
        Stage stage = new Stage();
        stage.setTitle("Menu de Empleados");
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

    /*** Other methods that load other menu entries ***/

這里有“產品”菜單,看起來像這樣。

產品選單

當我鍵入成本並設置利潤時,價格將使用onKeyEvent計算,格式為“ 123.456,99”。 反之亦然。

txtUtil.setOnKeyReleased(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            if (txtCosto.getText() != null && txtUtil.getText() != null && txtPrecio.getText() != null) {
                try {
                    costo = Double.parseDouble(txtCosto.getText());
                    util = Double.parseDouble(txtUtil.getText());
                    precio = (costo / (((util / 100) - 1) * (-1)));
                    txtPrecio.setText(String.valueOf(String.format("%.2f", precio)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                JOptionPane.showMessageDialog(null, "error en algo");
            }

        }
    });
        txtPrecio.setOnKeyReleased(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            if (txtCosto.getText() != null && txtUtil.getText() != null && txtPrecio.getText() != null) {
                try {
                    costo = Double.parseDouble(txtCosto.getText());
                    precio = Double.parseDouble(txtPrecio.getText());
                    util = ((costo / precio) - 1) * -100;
                    txtUtil.setText(String.valueOf((double) Math.round(util * 100) / 100));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                JOptionPane.showMessageDialog(null, "error");
            }
        }
    });
}

因此,當我在價格TextField中釋放密鑰時,會收到此錯誤(除其他外,此處不再贅述)。

java.lang.NumberFormatException: For input string: "21428,57"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at ajfmo.sislic.controlador.CProductos$3.handle(CProductos.java:164)
at ajfmo.sislic.controlador.CProductos$3.handle(CProductos.java:1)

我發現問題出在ajfmo.sislic.controlador.CProductos $ 3.handle(CProductos.java:164),但我發現真正的問題是場景所使用的默認語言環境,我改成了en並出現了問題消失了,但是如果我想保留默認語言環境而不出現該錯誤怎么辦?

除了將記錄保存到MySQL數據庫之外, 如果我更改了語言環境是否會有問題?

非常感謝您提前閱讀本文。

若要以與語言環境相關的方式(包括分組字符和與語言環境相關的十進制分隔符)將文本解析為數值,請使用DecimalFormat對象。

這是一個非常快速的演示,應該很容易適應您的應用程序:

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

public class DecimalFormatTest {

    public static void main(String[] args) throws ParseException {

        // use system default locale:
        // NumberFormat format = DecimalFormat.getInstance();

        // or specify the locale explicitly:
        NumberFormat format = DecimalFormat.getInstance(new Locale("es", "VE"));

        String text = "123.456,01" ;
        double value = format.parse(text).doubleValue();
        System.out.println("Parsed value as double: " +value);
        System.out.println("Value formatted again as text: " + format.format(value));
    }

}

這給出了輸出

Parsed value as double: 123456.01
Value formatted again as text: 123.456,01

Double.valueOf以及擴展名Double.parseDouble不考慮浮點數的國際表示形式。 Double.valueOf上的​​javadoc聲明以下內容:

要解釋浮點值的本地化字符串表示形式,請使用java.text.NumberFormat的子類。

要獲取NumberFormat的本地化版本,請使用其getInstance方法。 因此,代碼中的以下兩行

costo = Double.parseDouble(txtCosto.getText());
precio = Double.parseDouble(txtPrecio.getText());

應該改為

NumberFormat nf = NumberFormat.getNumberInstance(); // Use JVM default locale
costco = nf.parse(txtCosto.getText()).doubleValue();
precio = nf.parse(txtPrecio.getText()).doubleValue();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM