6
votes

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?

6
Why don't you just parse the double and check for value < 10000000000000? - Alvin Wong
\\. OR [.] Both works, but don't just write '.' - shuangwhywhy

6 Answers

14
votes

Don't forget to escape the dot.

if (check.matches("[0-9]{1,13}(\\.[0-9]*)?"))
5
votes

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.

2
votes

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

1
votes

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]*)?

1
votes

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.

0
votes

You can use \d+(\.\d*)? as below in kotlin language-

    val rawString = "Hi..  2345.97 ..Bye"
    val DOUBLE_PATTERN = Pattern.compile("\\d+(\\.\\d*)?")
    val matcher = DOUBLE_PATTERN.matcher(rawString)
    var filterNumber = 0.0
    if (matcher.find())
        filterNumber = matcher.group() // extracted number- 2345.97