Javafx:如何将组合框字符串转换为双精度

雅库布·尤斯扎克(Jakub Juszczak)

我正在寻找一种解决方案,以将我从组合框获得的字符串转换为双精度。

我对JavaFX相当陌生,并尝试将旧的swing项目转换为fx。

在Swing中,我有类似以下内容:

NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    nf.setMinimumFractionDigits(2);

    String stringPrice = jTextFieldPrice.getText();

    try {
        double size= nf.parse(jComboboxSize.getItemAt(jComboboxSize.getSelectedIndex()).toString()).doubleValue();          
        double price= nf.parse(stringPrice).doubleValue();
        double newPrice= price * size;
...

到目前为止,我的FX代码

@FXML
private ComboBox<String> bottleSize;
@FXML
private TextField txfBottlePrice;

ObservableList<String> bottleList = FXCollections.observableArrayList(
    "0,187", 
    "0,25", 
    "0,375", 
    "0,5", 
    "0,62", 
    "0,7", 
    "0,75", 
    "0,8", 
    "1", 
    "1,5" 
);

....
....
   String sPrice = txfBottlePrice.getText();

    try {
         double dSize = Double.parseDouble(bottleSize.getValue());
         double dPrice = Double.parseDouble(sPrice);
         double newPrice = dPrice * dSize;

         txfPriceLiter.setText(Double.toString(newPrice));

    }catch ( NumberFormatException e) {
        System.out.println("Something went wrong!");
    }

但是...它不起作用。

雅库布·尤斯扎克(Jakub Juszczak)

谢谢!我很困惑,因为起初我尝试使用旧的NumberFormat代码,但是NumberFormat是未知的,并且Netbeans不想导入它。因此,我认为JavaFX中不提供该功能。但是在我粘贴了代码之后,它以某种方式识别了它并导入了程序包。

现在可以了。

 NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
    nf.setMaximumFractionDigits(2);
    nf.setMinimumFractionDigits(2);


    try {
        double dSize = nf.parse(bottleSize.getValue()).doubleValue();
        double dPrice = nf.parse(txfBottlePrice.getText()).doubleValue();
        double newPrice = dPrice * dSize;
        txfPriceLiter.setText(nf.format(newPrice));
    } catch (java.text.ParseException ex) {
       Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章