Search code examples
javanumberformatexception

NumberFormatException while parsing a Number


String str="123456.7855456677";
ParsePosition parsePosition = new ParsePosition(0);
NumberFormat numberFormat=new DecimalFormat();
Number number=numberFormat.parse(str, parsePosition);

if(parsePosition.getIndex()!=str.length())
{
    throw new IllegalArgumentException();
}

numberFormat.setMaximumFractionDigits(2);
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
double value=Double.parseDouble(numberFormat.format(number));
System.out.println(value);

The value of the String type variable str in this segment of code can be any dynamic value, assuming a user is free to input any string.

The Double.parseDouble() method on the second last line causes the java.lang.NumberFormatException to be thrown.

Removing the line numberFormat.setMaximumFractionDigits(2); and setting a RegEx to the overloaded constructor of the DecimalFormat class instead as usual like,

NumberFormat numberFormat=new DecimalFormat("#.##");

suppresses the exception.

So, why doesn't it work otherwise?


Solution

  • If you can debug the code then check out put of this line numberFormat.format(number) it gives a number containing a comma that might becoming reason for exception, check this 123,456.79 and this comma should not be there... hope this will help.