In my angular application I have to show number with minimum of 2 decimal places points, a maximum of 5 decimal points with commas .
Here is my code which is working fine for commas , but its working for 2 decimal places maximum, which should be 5 and it doesn't show 2 decimal automatically till user enter
private FormatNumber(value) {
const valArray = value === null ? this.el.nativeElement.value.split('.') : value.split('.');
for (let i = 0; i < valArray.length; ++i) {
valArray[i] = valArray[i].replace(/D/g, '');
}
let newVal = '';
if (valArray.length === 0) {
newVal = '';
} else {
const matches = valArray[0].match(/[0-9]{3}/gim);
if (matches !== null && valArray[0].length > 3) {
const commaGroups = Array.from(
Array.from(valArray[0])
.reverse()
.join('')
.match(/[0-9]{3}/gim)
.join()
)
.reverse()
.join('');
const replacement = valArray[0].replace(commaGroups.replace(/D/g, ''), '');
newVal = (replacement.length > 0 ? replacement + ',' : '') + commaGroups;
} else {
newVal = valArray[0];
}
if (valArray.length > 1) {
newVal += '.' + valArray[1].substring(0, 2);
}
}
const modelValue = newVal.replace(/,/g, '');
if (modelValue !== this.model.control.value) {
this.model.control.setValue(modelValue);
}
setTimeout(() => {
if (this.el.nativeElement.value !== newVal) {
this.el.nativeElement.value = newVal;
}
}, 0);
}
question from:
https://stackoverflow.com/questions/65857269/format-the-number-to-have-minimum-of-2-decimal-points-a-maximum-of-5-decimal-po 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…