Search code examples
javanumberformatexceptionparsefloat

Java Parsefloat Exception with a string that is number followed by characters


When I run this line of code: Float.parseFloat("1460000 JPY") I get the error

Exception in thread "main" java.lang.NumberFormatException: For input string: "1460000 JPY"

This string is coming from an API call from a form where this is a text field with no validation. It usually works because people put in just a number, but sometimes you get this issue. How do I get it to return just the initial numbers as a float and disregard the trailing alpha characters?


Solution

  • UPDATE: to account for the bug that @Tom brought up:

    Float.parseFloat("1.46 JPY".replaceAll("[^0-9.]",""));
    

    1.46

    the above is a superior solution. See below for explanation.

    As @azurefrog said, stripping out non-numeric characters and then parsing what is left as a Float is the way to go.You can accomplish this using the following code:

    Float.parseFloat("1460000 JPY".replaceAll("[^0-9]",""));
    

    1460000.0

    This is not very robust though, because for inputs like "1.46" the output becomes

    146.0

    .replaceAll("[^0-9.]","") fixes this inaccuracy by adding the decimal . character to the exclusion regex like so [^0-9.]