Is it possible to parse BigDecimal from a textfield ? I have seen some code where they parse bigdecimal from strings. But is it also possible to use this on textfield. I have worked out some code to make it work. But i have no idea if i should do it this way.
Float price = Float.parseFloat(textFieldInvoiceServicePrice.getText());
String servicetext = textFieldInvoiceService.getText();
BigDecimal priceExcl= BigDecimal.valueOf(price);
No, that's not how you should do it - you're currently parsing from a string to float, then converting that float to a BigDecimal
. You clearly know how to get a string from a text field, because you're already doing it in the first line - you can just do that with BigDecimal
instead:
BigDecimal price = new BigDecimal(textFieldInvoiceServicePrice.getText());
However, you should note that this won't be culture-sensitive - it will always use .
as the decimal separator, for example. You should use NumberFormat
if you want culture-sensitive parsing.
See more on this question at Stackoverflow