2

I'm using a NumberFormat instance to parse text using default locale.

If a string is not a valid numeric value, I have to return 0. The problem is that parse method,according to Javadocs:

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, if I parse (I'm using italian locale) "BAD 123,44" I correctly get a ParseException and return 0, but if I parse "123,44 BAD", I get a value of 123.44, while I have to return 0 in this case. And worse, if I parse "123.44 BAD", I get value 12344!

 class RateCellReader {
      public static final NumberFormat NUMBER_FORMAT =
          NumberFormat.getNumberInstance(Locale.getDefault());

      ...

      try {
         number = NUMBER_FORMAT.parse(textValue);
      } catch (ParseException e) {
         number = 0;
      }

      ...
 }

How can I do an exact parse of text, or check if text correctly represent a number in default locale?

EDIT:

Getting inspired by the response linked by @yomexzo, I changed my code like this:

 class RateCellReader {
      public static final NumberFormat NUMBER_FORMAT =
          NumberFormat.getNumberInstance(Locale.getDefault());

      ...


      ParsePosition pos = new ParsePosition(0);
      number = NUMBER_FORMAT.parse(textValue,pos);
      if (textValue.length() != pos.getIndex())
          number = 0;


      ...
 }
Andrea Parodi
  • 5,534
  • 27
  • 46

1 Answers1

2

How about this

    boolean isValid;
    try {
        Number n = NUMBER_FORMAT.parse(s1);
        String s2 = NUMBER_FORMAT.format(n);
        isValid = s1.equals(s2);
    }catch(ParseException e) {
        isValid = false;
    }
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • this fail to correctly parse values as "1234,56", because the formatter reformat them as "1.234,56". Or, if we use a format string without thousand separator, we got the opposite problem, with "1.234,56" reformatted as "1234,56" – Andrea Parodi Jun 13 '13 at 16:27
  • right, it was just an idea, the issues you mentioned seem to be fixable – Evgeniy Dorofeev Jun 13 '13 at 16:52
  • Sure, but I feel the code I dervide from the answer linked by @yomexzo is simpler, more elegant and maybe faster (we avoid a reformat of the value) – Andrea Parodi Jun 13 '13 at 16:55