Problem in converting number (NumberFormat)

6

I'm having the following difficulty, getting a value through my form:

Double salario = Double.parseDouble(request.getParameter("salario"));

Since the value entered by the user will be something like: 2.687,35 . And this value, I will compare with some other%% variables as well.

However, double this method expects the data to be in the American format and without thousands separators.

So I used Double.parseDouble as follows:

String salario = request.getParameter("salario");
NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("pt","BR")); 
Double s = nf.parse(salario).doubleValue();

On line:

Double s = nf.parse(salario).doubleValue();

Give the following error:

unreported exception exception must be caught or declared to be thrown

I have tried to put it inside NumberFormat and it continues with the same message.

    
asked by anonymous 22.04.2014 / 20:07

1 answer

7

The catch(ParseException) is sufficient to handle the error and avoid the compiler message. If your Java continued to report the cited exception it could be for some other error, for example:

  • Failed to save file to your IDE recompile class
  • Failed to recompile class for some other reason
  • There is another error in the class preventing the parser from updating your IDE

As for your code, I tested the NumberFormat the way it is in the question and it can not parse the 2.687,35 value because the currency format requires the currency prefix. However, if the value is R$ 2.689,35 it succeeds.

See a working example:

public class TestDouble {
    public static void main( String[ ] args ) throws ParseException {
        String salario = "R$ 2.689,35";
        NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("pt", "BR" ));
        System.out.println( nf.parse( salario ) );
    }
}

If you want to parse without the currency symbol, just use the getInstance method instead of getCurrencyInstance . Example:

public class TestDouble {
    public static void main( String[ ] args ) throws ParseException {
        String salario = "2.689,35";
        NumberFormat nf = NumberFormat.getInstance(new Locale("pt", "BR" ));
        System.out.println( nf.parse( salario ) );
    }
}
    
22.04.2014 / 20:25