I have an Ionic 3 App where I want to format all currency input field to a formal way. If I input 10,000 it should show to the field like this: PHP 10,000.00 and if hundreds it should show like this: PHP 100.00.
I also want to handle the backspace or clear button in Ionic when inputting a field so I can handle that in Android or iOS which I couldn't google to find some solutions or answer.
I already have found some reference in jQuery style with a jsfiddle on it.
But when I translate the code into Angular/Ionic way it didn't solve my problem.
Here is my code below in my ts file
handleCurrency(e) {
console.log(e)
if (e.keyCode == 8 && this.form.value.amount.length > 0) {
this.form.value.amount = this.form.value.amount.slice(0, this.form.value.amount.length - 1); //remove last digit
this.form.value.amount = this.formatNumber(this.form.value.amount);
}
else {
let key = this.getKeyValue(e.keyCode);
if (key) {
this.form.value.amount += key; //add actual digit to the input string
this.form.value.amount = this.formatNumber(this.form.value.amount); //format input string and set the input box value to it
}
}
// return false;
}
getKeyValue(keyCode) {
if (keyCode > 57) { //also check for numpad keys
keyCode -= 48;
}
if (keyCode >= 48 && keyCode <= 57) {
return String.fromCharCode(keyCode);
}
}
formatNumber(input) {
if (isNaN(parseFloat(input))) {
return "0.00"; //if the input is invalid just set the value to 0.00
}
let num = parseFloat(input);
return (num / 100).toFixed(2); //move the decimal up to places return a X.00 format
}
and in my html
<ion-input type="number" formControlName="amount" min="0.01" step="0.01" value="0.00" (keypress)="handleCurrency($event)" placeholder=""></ion-input>
There are no errors in the code. But it doesn't work or it didn't automatically put decimal place between hundreds or thousands.
Can someone shed some light for me? Thanks in advance.