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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Duane
  • 1,980
  • 4
  • 17
  • 27

6 Answers6

14

Don't forget to escape the dot.

if (check.matches("[0-9]{1,13}(\\.[0-9]*)?"))
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 2
    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. – Duane Jan 28 '13 at 13:37
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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
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

stema
  • 90,351
  • 20
  • 107
  • 135
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]*)?

Trenton D. Adams
  • 1,805
  • 2
  • 16
  • 20
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.

august0490
  • 777
  • 1
  • 9
  • 15
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
Deepak
  • 381
  • 4
  • 3