-1

I need to match Regex for an input text. It should allow only numbers and only one dot.

Below is my pattren.

(?!\s)[0-9\.\1]{0,}

This is allowing only numbers and allowing multiple dots. How to write so that it should allow only one dot?

Bascially when i enter decimal, i need to round off to whole number.

Matarishvan
  • 2,382
  • 3
  • 38
  • 68
  • /^\d+(\.\d+)?$/ answer obtained from: [here](https://stackoverflow.com/questions/18149155/allow-only-a-single-point-in-decimal-numbers) – RyeRai Mar 22 '18 at 04:34
  • Possible duplicate of [Simple regular expression for a decimal with a precision of 2](https://stackoverflow.com/questions/308122/simple-regular-expression-for-a-decimal-with-a-precision-of-2) – Herohtar Mar 22 '18 at 04:40
  • Also, see [this answer](https://stackoverflow.com/questions/2811031/decimal-or-numeric-values-in-regular-expression-validation/39399503#39399503) – Herohtar Mar 22 '18 at 04:40

2 Answers2

1

In case you dont mind accepting just a point, this should do it

\d*\.\d*

Otherwise, the more complete answer could look like this:

\d*\.\d+)|(\d+\.\d*)
iagowp
  • 2,428
  • 1
  • 21
  • 32
0

You can use the following regex to select your integer and fractional parts than add 1 to your integer part depending to your fractional part:

Regex: ^(\d+)\.(\d+)$

In use:

function roundOff(str) {
  return str.replace(/^(\d+)\.(\d+)$/g, ($0, $1, $2) => $2.split('')[0] >= 5 ? parseInt($1) + 1 : parseInt($2)); 
}

var str1 = roundOff('123.123') 
console.log(str1); // 123

var str2 = roundOff('123.567')
console.log(str2); // 124
guijob
  • 4,413
  • 3
  • 20
  • 39
  • But how do i restrict multiple dots? – Matarishvan Mar 22 '18 at 04:40
  • @Matarishvan It's already doing it. This regex will only match strings which contains a single dot between digits. If your string has multiple dots than this regex will not match at all. – guijob Mar 22 '18 at 04:44
  • This is allowing multiple dots. Its failing – Matarishvan Mar 22 '18 at 05:06
  • Could you edit my regex linked in my previous comment adding a case where multiple dots are matched? I'll really appreciate that. [link is here again](https://regex101.com/r/uwmcvJ/1) – guijob Mar 22 '18 at 05:32