SimpleGuy
SimpleGuy

Reputation: 2894

Problematic decimalFormat.parse() in Java

There is a requirement that if user enters a number, parse it and doSomething(). If user enters a mixture of number and string, then doSomethingElse()

So, I wrote the code as under:

String userInput = getWhatUserEntered();
try {
   DecimalFormat decimalFormat = (DecimalFormat)     
   NumberFormat.getNumberInstance(<LocaleHere>);
   Number number = decimalFormat.parse(userInput);
   doSomething(number);    // If I reach here, I will doSomething

   return;
}
catch(Exception e)  {
  // Oh.. user has entered mixture of alpha and number
}

doSomethingElse(userInput);  // If I reach here, I will doSomethingElse
return;

The function getWhatUserEntered() looks as under

String getWhatUserEntered()
{
  return "1923";
  //return "Oh God 1923";
  //return "1923 Oh God";
}

But, there is a problem.

Is there any inbuilt (better) function to the thing I want to achieve ? Can my code be modified to suit needs ?

Upvotes: 1

Views: 140

Answers (3)

gapvision
gapvision

Reputation: 1029

You better use some regex e.g. userInput.matches("[0-9]+") for matching numbers only

Upvotes: 3

Olivier Gr&#233;goire
Olivier Gr&#233;goire

Reputation: 35427

DecimalFormat accepts any string if it starts with a number.

What you can do is perform an additional check.

try {
  DecimalFormat decimalFormat = (DecimalFormat)     
  NumberFormat.getNumberInstance(<LocaleHere>);
  Number number = decimalFormat.parse(userInput);
  if (number.toString().equals(userInput)) {
    doSomething(number);    // If I reach here, I will doSomething   
    return;
  }
}

Upvotes: 2

babanin
babanin

Reputation: 3584

Everything is OK due to specific DecimalFormat implementation. JavaDoc says:

Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.

So you have to fix your code to something like this:

  String userInput = getWhatUserEntered();
    try {
        NumberFormat formatter = NumberFormat.getInstance();
        ParsePosition position = new ParsePosition(0);
        Number number = formatter.parse(userInput, position);
        if (position.getIndex() != userInput.length())
            throw new ParseException("failed to parse entire string: " + userInput, position.getIndex());
        doSomething(number);    // If I reach here, I will doSomething

        return;
    }
    catch(Exception e)  {
        // Oh.. user has entered mixture of alpha and number
    }

    doSomethingElse(userInput);  // If I reach here, I will doSomethingElse
    return;

Upvotes: 4

Related Questions