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!
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);
}