0

As Given below I have to write one method in java before calculation performing. I am going to check if that string contains only numbers, but if I am going to enter floating points values it will not going to validate it.

Please suggest me right source code for it.

if (Purchase_Paid.getText().matches("[0-9]+")) {
    Global_Total = Float.parseFloat(Purchase_Amount.getText());
    Globle_paidAmount = Float.parseFloat(Purchase_Paid.getText());
    GlobleOutStandingAmount = (Global_Total - Globle_paidAmount);
    Purchase_Outstanding.setText(String.valueOf(GlobleOutStandingAmount));
} else {
    Alert alert = new Alert(Alert.AlertType.WARNING);
    alert.setTitle("Validation");
    alert.setHeaderText(null);
    alert.setContentText("Please enter only numbers in Paid fields");
    alert.showAndWait();

}
mark42inbound
  • 364
  • 1
  • 4
  • 19
  • Possible duplicate of [Decimal or numeric values in regular expression validation](https://stackoverflow.com/questions/2811031/decimal-or-numeric-values-in-regular-expression-validation) – craigcaulfield May 14 '18 at 06:18

2 Answers2

0

you check if string is numeric like this

if (Purchase_Paid.getText().matches("^[-+]?\\d+(\\.\\d+)?$")){

}
hakim
  • 3,819
  • 3
  • 21
  • 25
0

Regular expression [0-9]+ will only match for numbers in your text. If you want to allow floating point numbers too, then use following regex

[+-]?([0-9]*[.])?[0-9]+

if (Purchase_Paid.getText().matches("[+-]?([0-9]*[.])?[0-9]+")) {
    //Take Necessary action
}
Sagar
  • 23,903
  • 4
  • 62
  • 62