3

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!

petehallw
  • 1,014
  • 6
  • 21
  • 49

2 Answers2

3

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);
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • If I had mixed them up wouldn't I receive a compile-time error? The variable in my example (`total_ff`) is of type `Double`. Confused as to why it says it's a string in the exception though... – petehallw Dec 19 '16 at 08:43
  • Because these are two distinct things. The risen exception is not related to the `parse()` method call. The problem happens in the `Double` constructor invocation : `Double nCount = new Double("15,7");` which rises the exception. `Double nCount = new Double("15.7");` works. I said you mix because you format a `Double` as a `String` in a specific Locale format and you use this `String` to instantiate a `Double`. You should not do it since the `Double` constructor is independent of the `Locale`. Also, just an advise : the next time you should post all required code. It eases the understanding. – davidxxx Dec 19 '16 at 11:31
0

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!

Rob Pridham
  • 4,780
  • 1
  • 26
  • 38