8

Is there a better, more elegant (and/or possibly faster) way than

boolean isNumber = false;
try{
   Double.valueOf(myNumber);
   isNumber = true;
} catch (NumberFormatException e) {
}

...?


Edit: Since I can't pick two answers I'm going with the regex one because a) it's elegant and b) saying "Jon Skeet solved the problem" is a tautology because Jon Skeet himself is the solution to all problems.

3
  • That's the way I've done things when user input is required to be a number. Never came across anything else however. Dec 11, 2008 at 14:58
  • I asked a very similar question a while back. Some of those answers might help. stackoverflow.com/questions/237159/… Dec 11, 2008 at 16:03
  • Jajajajaja good answer Epaga.
    – Agusti-N
    Dec 11, 2008 at 19:15

11 Answers 11

10

I don't believe there's anything built into Java to do it faster and still reliably, assuming that later on you'll want to actually parse it with Double.valueOf (or similar).

I'd use Double.parseDouble instead of Double.valueOf to avoid creating a Double unnecessarily, and you can also get rid of blatantly silly numbers quicker than the exception will by checking for digits, e/E, - and . beforehand. So, something like:

public boolean isDouble(String value)
{        
    boolean seenDot = false;
    boolean seenExp = false;
    boolean justSeenExp = false;
    boolean seenDigit = false;
    for (int i=0; i < value.length(); i++)
    {
        char c = value.charAt(i);
        if (c >= '0' && c <= '9')
        {
            seenDigit = true;
            continue;
        }
        if ((c == '-' || c=='+') && (i == 0 || justSeenExp))
        {
            continue;
        }
        if (c == '.' && !seenDot)
        {
            seenDot = true;
            continue;
        }
        justSeenExp = false;
        if ((c == 'e' || c == 'E') && !seenExp)
        {
            seenExp = true;
            justSeenExp = true;
            continue;
        }
        return false;
    }
    if (!seenDigit)
    {
        return false;
    }
    try
    {
        Double.parseDouble(value);
        return true;
    }
    catch (NumberFormatException e)
    {
        return false;
    }
}

Note that despite taking a couple of tries, this still doesn't cover "NaN" or hex values. Whether you want those to pass or not depends on context.

In my experience regular expressions are slower than the hard-coded check above.

10
  • In my experience, I usually want the Double and to know if it's a legal double or not, so I'd probably change your method to return Double or throw a NumberFormatException. Dec 11, 2008 at 15:13
  • ..or return a tiny class with a boolean and a double, or use an out-of-bounds double, depending on the need. Dec 11, 2008 at 15:14
  • 1
    @Paul: Indeed. At that point you've basically implemented .NET's "bool Double.TryParse(string text, out double). In Java an alternative would be to return a Double (object) or null for "invalid".
    – Jon Skeet
    Dec 11, 2008 at 15:18
  • Pssst... +1.0e-7 is a valid double.
    – plinth
    Dec 11, 2008 at 15:41
  • Pssst... it will still fail. There are two possible signs in a double: preceding the mantissa and after the e/E, and a sign can be a '+'. There's actually a lesson here, which is that the spec for a double is more complicated than your code: better to do if ("0123456789eE-+".Contains(c)) continue;
    – plinth
    Dec 11, 2008 at 15:49
9

You could use a regex, i.e. something like String.matches("^[\\d\\-\\.]+$"); (if you're not testing for negative numbers or floating point numbers you could simplify a bit).

Not sure whether that would be faster than the method you outlined though.

Edit: in the light of all this controversy, I decided to make a test and get some data about how fast each of these methods were. Not so much the correctness, but just how quickly they ran.

You can read about my results on my blog. (Hint: Jon Skeet FTW).

9
  • It would also fail for negative numbers and non-integers :)
    – Jon Skeet
    Dec 11, 2008 at 15:04
  • Has anybody tested to see if a regexp is faster or slower than Jon Skeet's method below? The regexp certainly looks cleaner if you can find one that works for the numbers you expect. Dec 11, 2008 at 15:15
  • Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. ;) Dec 11, 2008 at 15:26
  • @Paul: I did tests with .NET ages ago and regexes were significantly slower. If you want to use a regex, at least built it once and compile it :) (I suspect it will still be slower though. Btw, my code now covers a few more cases than it originally did, and it's starting to get complicated...)
    – Jon Skeet
    Dec 11, 2008 at 15:47
  • both this answer and john skeet's presume that the decimal separator is . and you do not allow thousands separators either. Dec 11, 2008 at 18:59
8

See java.text.NumberFormat (javadoc).

NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
Number myNumber = nf.parse(myString);
int myInt = myNumber.intValue();
double myDouble = myNumber.doubleValue();
2
  • 1
    It's nice to see an answer that doesn't make locale assumptions. +1
    – J c
    Dec 12, 2008 at 16:21
  • "Global community" - you have to have proper locale formatting / parsing. 1.024,00 in Germany is 1 024.00 in Paris and 1,024.00 in New York.
    – Ran Biron
    Dec 14, 2008 at 6:58
5

The correct regex is actually given in the Double javadocs:

To avoid calling this method on an invalid string and having a NumberFormatException be thrown, the regular expression below can be used to screen the input string:

    final String Digits     = "(\\p{Digit}+)";
    final String HexDigits  = "(\\p{XDigit}+)";
    // an exponent is 'e' or 'E' followed by an optionally 
    // signed decimal integer.
    final String Exp        = "[eE][+-]?"+Digits;
    final String fpRegex    =
        ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
         "[+-]?(" + // Optional sign character
         "NaN|" +           // "NaN" string
         "Infinity|" +      // "Infinity" string

         // A decimal floating-point string representing a finite positive
         // number without a leading sign has at most five basic pieces:
         // Digits . Digits ExponentPart FloatTypeSuffix
         // 
         // Since this method allows integer-only strings as input
         // in addition to strings of floating-point literals, the
         // two sub-patterns below are simplifications of the grammar
         // productions from the Java Language Specification, 2nd 
         // edition, section 3.10.2.

         // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
         "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+

         // . Digits ExponentPart_opt FloatTypeSuffix_opt
         "(\\.("+Digits+")("+Exp+")?)|"+

   // Hexadecimal strings
   "((" +
    // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
    "(0[xX]" + HexDigits + "(\\.)?)|" +

    // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
    "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +

    ")[pP][+-]?" + Digits + "))" +
         "[fFdD]?))" +
         "[\\x00-\\x20]*");// Optional trailing "whitespace"

    if (Pattern.matches(fpRegex, myString))
        Double.valueOf(myString); // Will not throw NumberFormatException
    else {
        // Perform suitable alternative action
    }

This does not allow for localized representations, however:

To interpret localized string representations of a floating-point value, use subclasses of NumberFormat.

3

Use StringUtils.isDouble(String) in Apache Commons.

1
  • Moved in newer versions. See org.apache.commons.lang3.math.NumberUtils. In particular NumberUtils.isParseable() and NumberUtils.isCreatable(). Apr 7, 2017 at 16:26
3

Leveraging off Mr. Skeet:

private boolean IsValidDoubleChar(char c)
{
    return "0123456789.+-eE".indexOf(c) >= 0;
}

public boolean isDouble(String value)
{
    for (int i=0; i < value.length(); i++)
    {
        char c = value.charAt(i);
        if (IsValidDoubleChar(c))
            continue;
        return false;
    }
    try
    {
        Double.parseDouble(value);
        return true;
    }
    catch (NumberFormatException e)
    {
        return false;
    }
}
1
  • Trying this for 1 gets me false when it should be true :P
    – test
    Aug 20, 2014 at 4:44
2

Most of these answers are somewhat acceptable solutions. All of the regex solutions have the issue of not being correct for all cases you may care about.

If you really want to ensure that the String is a valid number, then I would use your own solution. Don't forget that, I imagine, that most of the time the String will be a valid number and won't raise an exception. So most of the time the performance will be identical to that of Double.valueOf().

I guess this really isn't an answer, except that it validates your initial instinct.

Randy

2
  • I like the regex approach. While it's true that the one's presented may not be correct for the OP's requirements, that's simply because the requirements are vague. Presenting the way to develop the solution is the best we can do. Dec 11, 2008 at 15:31
  • I see what you're saying. If the goal is simply to detect digits, then [0-9]+ would work. Dec 16, 2008 at 14:46
2

I would use the Jakarta commons-lang, as always ! But I have no idea if their implementation is fast or not. It doesnt rely on Exceptions, which might be a good thig performance wise ...

2
  • commons-lang also detects things that Java doesn't, like: Multiple commas, whitespace around the number and some more. Dec 11, 2008 at 15:04
  • It depends what you want to do. There are numbers which aren't representable as Java doubles - should they be included or not? If you really want to know whether you'll eventually be able to convert to a Java double, I suspect you'll have a hard time doing so reliably without a call to Double.
    – Jon Skeet
    Dec 11, 2008 at 15:07
1

Following Phill's answer can I suggest another regex?

String.matches("^-?\\d+(\\.\\d+)?$");
1

I prefer using a loop over the Strings's char[] representation and using the Character.isDigit() method. If elegance is desired, I think this is the most readable:

package tias;

public class Main {
  private static final String NUMERIC = "123456789";
  private static final String NOT_NUMERIC = "1L5C";

  public static void main(String[] args) {
    System.out.println(isStringNumeric(NUMERIC));
    System.out.println(isStringNumeric(NOT_NUMERIC));
  }

  private static boolean isStringNumeric(String aString) {
    if (aString == null || aString.length() == 0) {
      return false;
    }
    for (char c : aString.toCharArray() ) {
      if (!Character.isDigit(c)) {
        return false;
      }
    }
    return true;
  }

}

-1

If you want something that's blisteringly fast, and you have a very clear idea of what formats you want to accept, you can build a state machine DFA by hand. This is essentially how regexes work under the hood anyway, but you can avoid the regex compilation step this way, and it may well be faster than a generic regex compiler.

1
  • Although this is a theoretically interesting answer, it isn't really useful here as you don't provide info on how to construct such a machine and use it in context.
    – opticyclic
    Apr 10, 2013 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.