当输入为number
类型时,我在格式化数字时遇到问题。我想要的是,当用户在字段中键入一些数字时,它应该是1000 -> 1,000
。这是我的代码示例:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'numberFormat',
})
export class NumberFormatPipe implements PipeTransform {
transform(val) {
if (val) {
val = this.format_number(val, '');
}
return val;
}
format_number(number, prefix) {
console.log('Value: ', number);
const thousand_separator = ',';
const decimal_separator = '.';
const regex = new RegExp('[^' + decimal_separator + '\\d]', 'g');
const number_string = String(number);
String(number_string).replace(regex, '').toString;
const split = number_string.split(decimal_separator);
const rest = split[0].length % 3;
let result = split[0].substr(0, rest);
const thousands = split[0].substr(rest).match(/\d{3}/g);
if (thousands) {
const separator = rest ? thousand_separator : '';
result += separator + thousands.join(thousand_separator);
}
result = split[1] !== undefined ? result + decimal_separator + split[1] : result;
return prefix === undefined ? result : (result ? prefix + result : '');
}
}