我正在寻找一种解决方案,将从组合框获得的字符串转换为 double 。
我对 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!");
}
但是......它不起作用。
最佳答案
如果您想显示逗号 (,),您可以考虑将 , 转换为 .在解析之前。
double dSize = Double.parseDouble(bottleSize.getValue().replace(",","."));
关于Javafx:如何将组合框字符串转换为 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27986341/