Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a string contains only digits and one occurrence of a decimal point?

My idea is something like this but I dont know the correct code

if (mystring.matches("[0-9.]+")){
  //do something here
}else{
  //do something here
}

I think I'm almost there. The only problem is multiple decimal points can be present in the string. I did look for this answer but I couldn't find how.

like image 569
user3320339 Avatar asked Feb 21 '14 01:02

user3320339


People also ask

How can you check if string contains only digits?

Use the test() method to check if a string contains only digits, e.g. /^[0-9]+$/. test(str) . The test method will return true if the string contains only digits and false otherwise.

Which function returns true if string contains only digits and false otherwise?

The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.

How do you check if a string contains only numbers JS?

To check if a string contains numbers in JavaScript, call the test() method on this regex: /\d/ . test() will return true if the string contains numbers. Otherwise, it will return false .


1 Answers

If you want to -> make sure it's a number AND has only one decimal <- try this RegEx instead:

if(mystring.matches("^[0-9]*\\.?[0-9]*$")) {
    // Do something
}
else {
    // Do something else
}

This RegEx states:

  1. The ^ means the string must start with this.
  2. Followed by none or more digits (The * does this).
  3. Optionally have a single decimal (The ? does this).
  4. Follow by none or more digits (The * does this).
  5. And the $ means it must end with this.

Note that bullet point #2 is to catch someone entering ".02" for example.

If that is not valid make the RegEx: "^[0-9]+\\.?[0-9]*$"

  • Only difference is a + sign. This will force the decimal to be preceded with a digit: 0.02
like image 142
Timeout Avatar answered Sep 24 '22 19:09

Timeout