Java regex on double
I'm trying to check for a double that has a maximum of 13 digits before the decimal point, and the decimal point and the numbers following it are optional. Thus, the user could write an integer or a number with decimal places.
For starters, I had this:
if (check.matches("[0-9](.[0-9]*)?"))
I went through several pages on Google and I was unable to get it to work despite various efforts. My thought was to do it like this, but it won't work:
[0-9]{1,13}(.[0-9]*)?
How can i do this?
Remember to avoid the point.
if (check.matches("[0-9]{1,13}(\\.[0-9]*)?"))
First of all you need to escape the dot (in java it will [0-9]{1,13}(\\.[0-9]*)?
). Secondly, do not forget that there is another popular view of doubles - scientific. So it is 1.5e+4
again a valid double. Finally, don't forget that a double number can be negative or have no whole part at all. For example. -1.3
and .56
are valid doubles.
You need to avoid the dot and you need at least the digit after the dot
[0-9]{1,13}(\\.[0-9]+)?
See here in Regexr
John's answer is close. But you need to add "-" if it is negative, if you accept negative values. So it will be changed to-?[0-9]{1,13}(\.[0-9]*)?
if you need to check for decimal with commas and negatives:
Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+[\\.\\,]{1}[0-9]+$", (CharSequence) testObject);
Good luck.