I'm trying to check for a double that has a maximum of 13 digits before the decimal point and the decimal point and numbers following it are optional. So the user could write a whole number or a number with decimals.
To start with I had this:
if (check.matches("[0-9](.[0-9]*)?"))
I've been through several pages on Google and haven't had any luck getting it working despite various efforts. My thought was to do it like this but it doesn't work:
[0-9]{1,13}(.[0-9]*)?
How can I do it?
Don't forget to escape the dot.
if (check.matches("[0-9]{1,13}(\\.[0-9]*)?"))
First of all you need to escape the dot(in java this would be [0-9]{1,13}(\\.[0-9]*)?
). Second of all don't forget there is also another popular representation of doubles - scientific. So this 1.5e+4
is again a valid double number. And lastly don't forget a double number may be negative, or may not have a whole part at all. E.g. -1.3
and .56
are valid doubles.
You need to escape the dot and you need at least on digit after the dot
[0-9]{1,13}(\\.[0-9]+)?
See it here on Regexr
John's answer is close. But a '-' needs to be added, in case it's negative, if you accept negative values. So, it would be modified to -?[0-9]{1,13}(\.[0-9]*)?
if you need to validate decimal with commas and negatives:
Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+[\\.\\,]{1}[0-9]+$", (CharSequence) testObject);
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With