-2

Here I made a text input which displays 1000 devided by the vlaue of text range:

<input type="range" name="rangeInput" min="50" max="200" onchange="updateTextInput(this.value);"><br>
<input type="text" id="fps" placeholder="fps" ><br>

<script>
function updateTextInput(val) {document.getElementById('fps').value=1000/val;}
</script>

The number results appear way beyond the decimal point. How can I limit the number of characters (for example 4 digits: 12.34) that appears on text input? maxlength doesn't seem to work here.

jack
  • 305
  • 1
  • 8
  • 1
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Nov 12 '20 at 09:38
  • You are not alone on this, https://stackoverflow.com/questions/18510845/maxlength-ignored-for-input-type-number-in-chrome – Supun De Silva Nov 12 '20 at 09:38
  • @Andreas this is inspiring, thanks. I should have known better – jack Nov 12 '20 at 11:01

1 Answers1

3

The .toFixed(x) method works, x=2 would limit to 2 decimals.

f = 12.456218;
a = f.toFixed(2);
console.log(a); // 12.45

If you want not only to limit the amount of decimals after the point but also the total number of digits, you will have to typecast to string and then work on that

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
WildWilyWilly
  • 121
  • 11