Search code examples
javajtextfield

Convert text input to int or double depending on input


I have a JFrame where I am taking the input from a text field and converting it to an Integer. I would also like to convert it to a double if it is a double and maybe return a message if it is neither a int or double. how can i do this?

My current code:

 int textToInt = Integer.parseInt(textField[0].getText());

Solution

  • String text = textField[0].getText();
    try {
        int textToInt = Integer.parseInt(text);
        ...
    } catch (NumberFormatException e) {
        try {
            double textToDouble = Double.parseDouble(text);
            ...
        } catch (NumberFormatException e2) {
            // message?
        }
    }
    

    To keep the precision, immediately parse to BigDecimal. This parseDouble of course is not locale specific.