To achieve the expected result, use below options of keyup
event
- On every key up, slit input value by '.'
- The first part of the split array will have value before the decimal point and the second part of the array will have value after decimal point
- Reassign input value based on length
component.html
<input type="text" (keyup)="onKeyup($event)" />
component.ts
onKeyup(e) {
const val = e.target.value.split(".");
if (!val[1]) {
e.target.value =
val[0].split("").length > 2
? e.target.value.substr(0, e.target.value.length - 1)
: e.target.value;
} else {
e.target.value =
val[1].split("").length > 2
? val[0] + "." + val[1].substr(0, val[1].length - 1)
: e.target.value;
}
}
working code sample for reference - https://codesandbox.io/s/angular-p1gh1
Updated code with HTML and javascript
codepen - https://codepen.io/nagasai/pen/xoLqdN?editors=1010
function onKeyup(e) {
const val = e.target.value.split(".");
if (!val[1]) {
e.target.value =
val[0].split("").length > 2
? e.target.value.substr(0, e.target.value.length - 1)
: e.target.value;
} else {
e.target.value =
val[1].split("").length > 2
? val[0] + "." + val[1].substr(0, val[1].length - 1)
: e.target.value;
}
}
<input type="text" onkeyup ="onKeyup(event)"/>