Format currency input in angular 2

[亡魂溺海] 提交于 2019-12-04 17:46:41

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.

Angular has a formatCurrency method

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('$', '') : '';
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!