6

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?

2
  • 1
    Why don't you just parse the double and check for value < 10000000000000? Commented Jan 28, 2013 at 13:32
  • 1
    \\. OR [.] Both works, but don't just write '.' Commented Jan 28, 2013 at 13:38

6 Answers 6

14

Don't forget to escape the dot.

if (check.matches("[0-9]{1,13}(\\.[0-9]*)?"))
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect thank you. I tried something similar but I was a bit naive to try use a regex checker online which can't accept "\\". Should have just tried it in the program.
5

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 Comments

It's for an accounting system exercise where we can't have negative numbers.
Any solution that handles all these cases ?
2

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

Comments

1

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.