简体   繁体   English

用前导零填充输入

[英]fill input with leading zeros

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.我用了面具=“0000000000”,但他没有回答我。 I have an input that allows up to 10 numbers, EX: 1234256896, that is 10 elements.我有一个最多允许 10 个数字的输入,例如:1234256896,即 10 个元素。 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.如果用户输入 12345,我必须在左边再添加 5 个零,因为他需要完成这 10 个数字,结果会是这样:0000012345。如果用户输入 123,他必须再添加 7 个零左边。

You can implement focusout event of input tag and format value withformat focusout

TS code TS代码

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 HTML

<input type="text" [(ngModel)]="mynumber" (focusout)="format()">

Demo https://stackblitz.com/edit/angular-format-number-leading-0演示https://stackblitz.com/edit/angular-format-number-leading-0

To get leading zero use array slice() method in javascript.要获得前导零,请使用 javascript 中的数组 slice() 方法。

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" .这将返回字符串"0000126534" You can revert back to initial number by using method parseInt()您可以使用方法parseInt()恢复为初始数字

 number = parseInt(number)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM