0

I needed a function in JavaScript that limited the input (form) of a number of a maximum of two decimals. So I found the following online:

function restrict(tis) {
  var prev = tis.getAttribute("data-prev");
  prev = (prev != '') ? prev : '';
  if (Math.round(tis.value * 100) / 100 != tis.value)
    tis.value = prev;
  tis.setAttribute("data-prev", tis.value)
}
<input type="number" name="amount" step="any" oninput="restrict(this);" required>

Honestly It's amazing, the input doesn't allow you more than two decimals, until by chance I entered only zeros, like this "100.000000000", if you enter only zeros as decimals it doesn't limit the field...

Is there anybody that has a fix for this? Thank you very much!

Elliot

Konrad
  • 21,590
  • 4
  • 28
  • 64
elliot
  • 13
  • 4
  • consider a number equality comparison function `function equal(x, y) { return Math.abs(x - y) < Number.EPSILON; }` ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON - not part of the question but still.. – Mark Schultheiss Dec 19 '22 at 17:07

2 Answers2

0

What if you use some regex ?

<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • This wouldn't provide a real time limit of two decimals during input, while with that function it does, except with zeros. – elliot Dec 19 '22 at 16:46
0

I borrowed the regex from the other answer

function restrict(tis) {
  let prev = tis.getAttribute("data-prev");
  prev = (prev != '') ? prev : '';
  if (!tis.value.match(/^\d*(\.\d{0,2})?$/))
    tis.value = prev;
  tis.setAttribute("data-prev", tis.value)
}
<input type="number" name="amount" step="any" oninput="restrict(this);" required>
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • Unfortunately they closed my question because they considered it to be a duplicate. The link that they provided includes answers with jQuery that it's not related to my question, and there was not a reasonable answer in that link. However, you answer is what I needed, so thank you, the only thing is that I had to replace const with let, so please edit your answer, thank you for your help. Have a nice day. – elliot Dec 19 '22 at 17:09
  • IF you truly believe it is a duplicate you should vote to close as a duplicate instead of just a new copy of that. ref: https://meta.stackoverflow.com/questions/402843/what-constitutes-a-duplicate-closure – Mark Schultheiss Dec 19 '22 at 17:10
  • My question is NOT a duplicate despite it was marked as duplicate by admins. While the other link doesn't not properly answer my question. – elliot Dec 19 '22 at 17:12
  • @elliot there is an answer in the duplicated question that do what you want, but without regex https://stackoverflow.com/a/69075763/5089567 – Konrad Dec 19 '22 at 17:26
  • Thank you @Konrad I didn't see that one. I added this with regex to my code, would you rather use the other one? – elliot Dec 19 '22 at 17:48