【发布时间】:2018-10-30 00:34:10
【问题描述】:
我有一个 Ionic 3 应用程序,我想将所有货币输入字段格式化为正式方式。如果我输入 10,000,它应该在字段中显示如下:PHP 10,000.00,如果输入数百,它应该显示如下:PHP 100.00。
我还想在输入字段时处理 Ionic 中的退格键或清除按钮,以便在 Android 或 iOS 中处理我无法通过 Google 找到的一些解决方案或答案。
我已经找到了一些 jQuery 风格的reference,上面带有jsfiddle。
但是当我将代码翻译成 Angular/Ionic 方式时,它并没有解决我的问题。
下面是我的 ts 文件中的代码
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
}
在我的html
中 <ion-input type="number" formControlName="amount" min="0.01" step="0.01" value="0.00" (keypress)="handleCurrency($event)" placeholder=""></ion-input>
代码中没有错误。但它不起作用,或者它没有自动将小数位放在数百或数千之间。
有人可以帮我解释一下吗?提前致谢。
【问题讨论】:
-
您是否考虑过使用
CurrencyPipe? angular.io/api/common/CurrencyPipe
标签: javascript angular ionic-framework ionic3 currency