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
Add a ment  | 

2 Answers 2

Reset to default 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./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