如何将文本字段解析为 bigdecimal

How to parse textfield to bigdecimal

是否可以从文本字段中解析 BigDecimal? 我看过一些代码,它们从字符串中解析 bigdecimal。 但是也可以在文本字段上使用它吗? 我已经制定了一些代码来使其工作。但是我不知道我是否应该这样做。

Float price = Float.parseFloat(textFieldInvoiceServicePrice.getText());
String servicetext = textFieldInvoiceService.getText();
BigDecimal priceExcl=  BigDecimal.valueOf(price);

不,这不是您应该做的 - 您当前正在从字符串解析为浮点数,然后将该浮点数转换为 BigDecimal。您清楚地知道如何从文本字段中获取字符串,因为您已经在第一行中这样做了——您可以只用 BigDecimal 代替:

BigDecimal price = new BigDecimal(textFieldInvoiceServicePrice.getText());

但是,您应该注意,这不会区分文化 - 例如,它将始终使用 . 作为小数点分隔符。如果你想要文化敏感的解析,你应该使用 NumberFormat

这是一个带有 属性、文本字段和转换器的示例:

public class MoneyParser extends Application {

    ObjectProperty<BigDecimal> money = new SimpleObjectProperty<BigDecimal>();

    @Override
    public void start(Stage primaryStage) {

        Group root = new Group();

        TextField textField = new TextField();

        // bind to textfield
        Bindings.bindBidirectional(textField.textProperty(), moneyProperty(), new MoneyStringConverter());

        // logging
        money.addListener((ChangeListener<Number>) (observable, oldValue, newValue) -> System.out.println("Money: " + newValue));

        root.getChildren().addAll(textField);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }

    public class MoneyStringConverter extends StringConverter<BigDecimal> {

        DecimalFormat formatter;

        public MoneyStringConverter() {
            formatter = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.US));
            formatter.setParseBigDecimal(true);
        }

        @Override
        public String toString(BigDecimal value) {

            // default
            if( value == null)
                return "0";

            return formatter.format( (BigDecimal) value);

        }

        @Override
        public BigDecimal fromString(String text) {

            // default
            if (text == null || text.isEmpty())
                return new BigDecimal( 0);

            try {

                return (BigDecimal) formatter.parse( text);

            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

        }
    }

    public final ObjectProperty<BigDecimal> moneyProperty() {
        return this.money;
    }

    public final java.math.BigDecimal getMoney() {
        return this.moneyProperty().get();
    }

    public final void setMoney(final java.math.BigDecimal money) {
        this.moneyProperty().set(money);
    }

}