typescript 以角度 2 格式化货币输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42092146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format currency input in angular 2
提问by Jane
I want to format input to USD currency as you type. The input will have 2 decimal places and will enter from right to left. Suppose if I type 54.60 it will be entered as $0.05-->$0.54-->$5.46-->$54.60. This PLUNKERexactly does this, but its in angular js. So far my directive looks like:
我想在您输入时将输入格式化为美元货币。输入将有 2 个小数位,将从右到左输入。假设如果我输入 54.60,它将被输入为 $0.05-->$0.54-->$5.46-->$54.60。这个PLUNKER正是这样做的,但它在 angular js 中。到目前为止,我的指令看起来像:
import {Directive, Output, EventEmitter} from '@angular/core';
import {NgControl} from '@angular/forms';
@Directive({
selector: '[formControlName][currency]',
host: {
'(ngModelChange)': 'onInputChange($event)',
'(keydown.backspace)':'onInputChange($event.target.value, true)'
}
})
export class CurrencyMask {
constructor(public model: NgControl) {}
@Output() rawChange:EventEmitter<string> = new EventEmitter<string>();
onInputChange(event: any, backspace: any) {
// remove all mask characters (keep only numeric)
var newVal = event.replace(/\D/g, '');
var rawValue = newVal;
var str = (newVal=='0'?'0.0':newVal).split('.');
str[1] = str[1] || '0';
newVal= str[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ',') + '.' + (str[1].length==1?str[1]+'0':str[1]);
// set the new value
this.model.valueAccessor.writeValue(newVal);
this.rawChange.emit(rawValue)
}
}
and in html it is being used as:
在 html 中它被用作:
<input name="cost" placeholder="cost" class="form-control" type="text" currency formControlName="cost" (rawChange)="rawCurrency=$event">
Update:
更新:
what finally worked for me is:
最终对我有用的是:
onInputChange(event: any, backspace: any) {
var newVal = (parseInt(event.replace(/[^0-9]/g, ''))/100).toLocaleString('en-US', { minimumFractionDigits: 2 });
var rawValue = newVal;
if(backspace) {
newVal = newVal.substring(0, newVal.length - 1);
}
if(newVal.length == 0) {
newVal = '';
}
else {
newVal = newVal;
}
// set the new value
this.model.valueAccessor.writeValue(newVal);
this.rawChange.emit(rawValue)
}
采纳答案by hakany
on input change use the following
在输入更改时使用以下内容
// remove dot and comma's, 123,456.78 -> 12345678
var strVal = myVal.replace(/\.,/g,'');
// change string to integer
var intVal = parseInt(strVal);
// divide by 100 to get 0.05 when pressing 5
var decVal = intVal / 100;
// format value to en-US locale
var newVal = decVal.toLocaleString('en-US', { minimumFractionDigits: 2 });
// or in singel line
var newVal = (parseInt(myVal.replace(/\.,/g, '')) / 100).toLocaleString('en-US', { minimumFractionDigits: 2 });
or
或者
use currency pipe to format to USD format by using only
使用货币管道格式化为美元格式,仅使用
var newVal = (parseInt(myVal.replace(/\.,/g, '')) / 100)
Hope this helps.
希望这可以帮助。
回答by Paul Story
Angular has a formatCurrency method
Angular 有一个 formatCurrency 方法
https://angular.io/api/common/formatCurrency
https://angular.io/api/common/formatCurrency
Here's how I've used it in my code:
这是我在代码中使用它的方式:
demand is a formControl
需求是一个表单控件
formatMoney(value: string) {
this.demand.setValue(
this.formatMoneyBase(value)
);
}
formatMoneyBase(value: string = ''): string {
return value.length ? formatCurrency(parseFloat(value.replace(/\D/g, '')), 'en', '$').replace('$', '') : '';
}