java – How can I tell if the first digit of a string is a number?

Question:

I have a form where I need to validate the tax number .

If it starts with PT or if it is a number without an acronym, I will validate it by the Portuguese finance algorithm, otherwise I will not.

What I wanted to know is how do I know if the first digit of the taxpayer number string is a number or not?

Answer:

It's simple, you need to take the first character and use the ready-made isDigit() .

Character.isDigit(x.charAt(0))

See working on ideone . And on repl.it. Also posted on GitHub for future reference .

In view of the user's observation in the comment below, if the rule is to consider that the digits are just Arabic decimal numbers, then just make a simple comparison:

x.charAt(0) >= '0' && x.charAt(0) <= '9'

See working on ideone . And on repl.it. Also posted on GitHub for future reference .

Obviously you can put this in a generic method to use anywhere. The method can receive the character that must be analyzed, which makes it very generic, or receive the string and the method itself choose the first character, which limits its use to the example mentioned in the question, but avoids extra work in the call.

I wouldn't go for other options that won't bring gains, only losses. They did some testing with some of them in C#, which should result in something similar to Java. This option of checking only Arabic numerals should be even faster, as well as simple.

Scroll to Top