Complete numbers with Javascript [closed]

-3

I'm stuck on an issue here and I need some help.

I need to autocomplete a bank ticket input.

Example:

12345.56789.00085.111111.11111.234566.6. 00000000000000

In this last field, if the user does not enter anything, he would have to autocomplete with "0".

If this was the case:

12345.56789.00085.111111.11111.234566.6. 123

The input would have to return:

12345.56789.00085.111111.11111.234566.6. 12300000000000

Always autocompleting with zeros to the right.

How can I do this in javascript?

    
asked by anonymous 25.07.2018 / 13:43

4 answers

1

You can use the repeat method of javascript to repeat the "0" n times according to the size of the string.
From what I noticed in your example, it should have a size of 14 (the last part), then:

var num = "123";
console.log(num + "0".repeat(14-num.length));
    
25.07.2018 / 13:50
1

The action of completing with a given caratere to a size is often referred to as pad . Javascript already has pad functions on both the left and right, which are padStart and padEnd respectively.

In your case using padEnd has the desired effect:

let boleto = "12345.56789.00085.111111.11111.234566.6.123";
let boletoCompletado = boleto.padEnd(54, "0");
console.log(boletoCompletado);

The first parameter of padEnd , 54 , indicates the number of characters to have, and the second parameter indicates caratere to be placed until the desired size.

If you need to support very old browsers where these two functions may not exist, you can use the polyfill mentioned in the documentation pages.

    
25.07.2018 / 15:16
0

Just do the .length of the string, and at the end if it is less than the desired number, for example:

if(input.length < 54)

does + = the number of 0s that can be done with a for loop of 54 - input.length (this is 54 the total number)

An example would be: (code may not compile, I'm not testing)

var textoInput = "";
(...)
if(textoInput.length < 54) {
   var zeros = "";
   for(int i = 0; i < (54 - TextoInpit.length); i++) {
       zeros += "0";
   }
   textoInput += zeros;
}
    
25.07.2018 / 13:48
0

You can do something like this, but you need to calculate the amount you want for zeros, and the amount you want to limit:

var numero="12345.56789.00085.111111.11111.234566.6.123", numero_repeticoes = numero.length, numero_remocoes = numero.length * 2;

var content = "0".repeat(numero_repeticoes).padStart(numero_remocoes, numero); (content).substring(54, -54);

Or simplify like this:

numero.padEnd(58, "0");

What I really do not know is the amount you want from zeros, so you should set a size limiter (limit your string) ...

    
25.07.2018 / 15:11