Search code examples
androidnumberformatexception

How to convert string value to integer?


 String servicePrice = serviceListArrayList.get(position).getPrice();
        System.out.println ("Price======>"+servicePrice);
        price = Integer.parseInt(servicePrice);
        System.out.println("IntPrice====>"+price);

I want to convert this servicePrice value to integer value but unfortunately got NumberFormatException,please help me from this error.


Solution

  • You will get a NumberFormatException if servicePrice is not a string representation of an integer (e.g. "1" or "123"). Examples include an empty string (""), text ("abc"), decimal numbers ("1.23"), currencies ("$1.23" or "$2"), or things that aren't valid numbers ("1.2.3" or "0..1")

    If you aren't in control of the string, you'll want to use appropriate checks to handle if a bad value is entered

    int val = 0;
    try {
        val = Integer.parseInt(str);
    }
    catch(NumberFormatException np) {
        // handle the case - e.g. error Toast message
    }