Search code examples
localedefaultnumber-formatting

Number format with Locale.getDefault() not giving expected result


I have this code:

public double stringToDouble(String s) {

       NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());

    try {

        return nf.parse(s).doubleValue();
    } catch (java.text.ParseException e) {
        return 0.0;
    }
}

Its working fine but with some values like 60.0 it gives 600.0 and I dont know why, with 60 it gives 60.0

Any suggestions? thanks in advance


Solution

  • OK, the answer is using this code:

    public double stringToDouble(String s) {
    
           NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
        nf.setGroupingUsed(false);
        ParsePosition parsePosition = new ParsePosition(0);
        Number n = nf.parse(s, parsePosition);
        if (n == null || parsePosition.getErrorIndex() >= 0 || parsePosition.getIndex() < s.length())
        {
          /* not a valid number */
        }
        return n.doubleValue();
    }
    

    use this instead of Double.parseDouble();