0

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!

Richard M.
  • 41
  • 5
  • 1
    Show the code what you have tried so far? – Sai M. Jul 10 '17 at 10:16
  • Possible duplicate of [How can I pad a value with leading zeros?](https://stackoverflow.com/questions/1267283/how-can-i-pad-a-value-with-leading-zeros) – maazadeeb Jul 10 '17 at 10:25
  • Possible duplicate of [Can't bind to 'ngModel' since it isn't a known property of 'input'](https://stackoverflow.com/questions/38892771/cant-bind-to-ngmodel-since-it-isnt-a-known-property-of-input) – The Hungry Dictator Jul 10 '17 at 10:27

5 Answers5

0
number=("0".repeat(9)+number).substr(-9);

Simply apply this to the inputs value on change.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

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!

bharadhwaj
  • 2,059
  • 22
  • 35
0

Your method is not optimal.

You can use the Slice() method to put into your string whatever you want.

I.E.:

('0' + '').slice(-2)
amin89
  • 558
  • 1
  • 8
  • 26
0
function pad(num, size) {
     var s = num+"";
     while (s.length < size) s = "0" + s;
     return s;
}

// usage
pad(123, 9)
engineforce
  • 2,840
  • 1
  • 23
  • 17
0
transform(val){
    let zeros = "000000000";
    return zeros.concat(val).slice(Math.min(val.toString().length * -1,-9));
}
Abdulrahman Alsoghayer
  • 16,462
  • 7
  • 51
  • 56