admin管理员组文章数量:1334162
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 plete 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.
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 plete 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.
Share Improve this question edited May 15, 2020 at 1:51 Lee Taylor 7,99416 gold badges37 silver badges53 bronze badges asked May 15, 2020 at 0:25 Eliemerson FonsecaEliemerson Fonseca 7573 gold badges12 silver badges35 bronze badges 1- Does this answer your question? How can I pad a value with leading zeros? – Lee Taylor Commented May 15, 2020 at 1:52
2 Answers
Reset to default 4You 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./edit/angular-format-number-leading-0
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)
本文标签: javascriptfill input with leading zerosStack Overflow
版权声明:本文标题:javascript - fill input with leading zeros - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742246050a2439566.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论