I'm in trouble but I can't find a correct way to do it. I used the mask = "0000000000", but he didn't answer me. I have an input that allows up to 10 numbers, EX: 1234256896, that is 10 elements. If the user enters 12345, I have to add 5 more zeros to the left, as he needs to complete the 10 numbers, the result would be like this: 0000012345. If the user enters 123, he will have to add 7 more zeros to the left.
Asked
Active
Viewed 5,083 times
2
-
Does this answer your question? [How can I pad a value with leading zeros?](https://stackoverflow.com/questions/1267283/how-can-i-pad-a-value-with-leading-zeros) – Lee Taylor May 15 '20 at 01:52
2 Answers
4
You can implement focusout
event of input tag and format
value with
TS code
format() {
this.mynumber = this.padLeft(this.mynumber, "0", 10);
}
padLeft(text: string, padChar: string, size: number): string {
return (String(padChar).repeat(size) + text).substr(size * -1, size);
}
HTML
<input type="text" [(ngModel)]="mynumber" (focusout)="format()">
Demo https://stackblitz.com/edit/angular-format-number-leading-0

Hien Nguyen
- 24,551
- 7
- 52
- 62
2
To get leading zero use array slice() method in javascript.
function getNumberWithLeadingZero(number) {
if (number<=9999999999) {
number = ("0000000000"+number).slice(-10);
}
return number;
}
This will return number with leading zero.
console.log(getNumberWithLeadingZero(126534));
This will return string "0000126534"
. You can revert back to initial number by using method parseInt()
number = parseInt(number)

Muhammad Saquib Shaikh
- 296
- 2
- 13