简体   繁体   中英

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:

If the user types only one number, I have to add some "0" before this number to reach value.length == 9

Example:
123 => 000000123

I'm using Angular 2 input forms and a pipe to transform the result.

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.

 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.

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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