NumberFormatException for input string: "15,7"

732 views Asked by At

I am getting a NumberFormatException when trying to parse a number such as "15,7". This would be "15.7" in US or UK format. I've attempted to retrieve the locale from the PC and parse based on that, as follows:

if (strCountry.equals("IT")) {
    locale = java.util.Locale.ITALIAN;
} else {
    locale = java.util.Locale.ENGLISH;
}

NumberFormat m_nf = NumberFormat.getInstance(locale);
m_nf.setMaximumFractionDigits(1);

From logging I've confirmed that the system returns "IT" as the country. The parsing is then attempted like this:

Double nCount = new Double(m_nf.format(total_ff));

However this is where the exception is thrown, due to a comma being used as a decimal point. Have I missed something? Thanks!

2

There are 2 answers

2
davidxxx On BEST ANSWER

I think you mix format() and parse() methods.

public final String format(double number) 

takes as parameter a number and returns a String.

public Number parse(String source) throws ParseException 

takes as parameter a String and return a number.

In your case, you have a String in a specific locale format and you want to retrieve the numeric value. So you should use parse() and not format().

Here is an example :

public static void main(String[] args) throws ParseException {
  Locale locale = java.util.Locale.ITALIAN;
  String valueString = "15,7";
  NumberFormat m_nf = NumberFormat.getInstance(locale);
  m_nf.setMaximumFractionDigits(1);
  Double number = (Double) m_nf.parse(valueString);
}
0
Rob Pridham On

Try this, or a variation thereof:

DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
DecimalFormat format = new DecimalFormat("#.0", symbols);
Double nCount = (Double) format.parse(total_ff);

Edit: corrected to parse as per other people's answers!