I need to implement thousands separator for an input in an Ionic app. I need to achieve this as user types them. I came with following implementation:
In Ts file:
public amount:string; // model
format(){
this.amount=this.separator(this.amount)
}
separator(amount)
{
var num_parts = amount.split(".");
num_parts[0] = num_parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return num_parts.join(".");
}
In html:
<ion-input [(ngModel)]="amount" (keyup)="format()" placeholder="Text Input"></ion-input>
It works fine till number of digit remains 4 (in numeric part).It goes bad when I have more than 4 digit. Since it is called on 'keyup' in second pass it adds another ',' after second digit like this:
1,2,345
And this continues: 1,2,3,455
How Can I get this implemented right ie adding thousand separator as user types them. Thanks for looking into this.
There was problem in my implementation : I was not removing previously added comma. See the comment in following snippet
separator(amount)
{
var num_parts = amount.split(".");
num_parts[0]= num_parts[0].replace(/,/g , ""); // I was not removing previously added comma
num_parts[0] = num_parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return num_parts.join(".");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.