[英]How to add recursively numbers before input value
This is probably very much a newbie question -- but i can't figure it out. 这可能是一个新手问题,但我不知道。
I have an input text with minlegth
9, and I have to do something like this: 我的输入文本为
minlegth
9,必须执行以下操作:
If the user types only one number, I have to add some "0"
before this number to reach value.length == 9
如果用户仅键入一个数字,则必须在此数字之前添加一些
"0"
以达到value.length == 9
Example:
123 => 000000123
I'm using Angular 2 input forms and a pipe to transform the result. 我正在使用Angular 2输入表单和管道来转换结果。
Can anyone help? 有人可以帮忙吗?
Here i've found the solution: 在这里,我找到了解决方案:
transform(val) {
var standardLength = "000000000";
return (standardLength + val).slice(-standardLength.length);
}
Thanks to everyone! 谢谢大家!
number=("0".repeat(9)+number).substr(-9);
只需将其应用于更改后的输入值。
If the length you want is always static (here 9), this is the easiest method. 如果所需的长度始终是静态的(此处为9),则这是最简单的方法。
num = [1, 11, 111, 1111, 11111]; for (var i = 0; i < 5; i++) { console.log(("000000000" + num[i]).substr(-9,9)); }
Hope this helps! 希望这可以帮助!
Your method is not optimal. 您的方法不是最佳方法。
You can use the Slice()
method to put into your string whatever you want. 您可以使用
Slice()
方法将字符串放入任意字符串中。
IE: IE:
('0' + '').slice(-2)
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
// usage
pad(123, 9)
transform(val){
let zeros = "000000000";
return zeros.concat(val).slice(Math.min(val.toString().length * -1,-9));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.