Problem in converting number (Numberformat)

Asked

Viewed 2,472 times

7

I’m having the following difficulty, picking up a value through my form:

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

Since the value typed by the user will be something like: 2.687,35. And this value, I will compare with some other variables double also.

However, Double.parseDouble this method expects the data to be in American format and without thousand separators.

So I used the NumberFormat as follows:

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

On the line:

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

From The Following Mistake:

unreported exception exception must be caught or declared to be thrown

I’ve tried to put inside the try/catch and continues with the same message.

  • could show your code with the try-catch?

  • It looks like this: Double s; //Try { s = nf.parse(salary). doubleValue(); } catch (Parseexception ex) { ex.printStackTrace(); }

1 answer

8


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

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

As for your code, I ran a test on Numberformat the way it’s on the question and he can’t parse the value 2.687,35, because the currency format requires the prefix of the respective currency. However, if the value is R$ 2.689,35 he can do.

See a functional 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 method getInstance 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 ) );
    }
}
  • 3

    if you want to show the documentation where you say ParseException is sufficient: http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html#parse%28java.lang.String%29

Browser other questions tagged

You are not signed in. Login or sign up in order to post.