Complete number with "zeros" until the total size is 9!

Asked

Viewed 639 times

9

I receive by parameter one Number.. ex: 18 and need to complement it with "zeros" until the total size is 9 numbers.. the result would be 180000000.

If the value received is 678 for example, the result would be 678000000.

NOTE: If the received parameter has 9 digits nothing should happen!

let number = 18;
let count = number.toString().length;

for (let i = count; i < 9; i++) {
  number = number.toString() + '0';
}

number = parseInt(number);

console.log(number);

I was able to solve it as follows, is there any simpler and more performative way to do the same algorithm?

  • 2

    And if you don’t put zeros on the right, if the number has more than 9 digits, it would exceed the limit of 9?

  • No, it can never exceed 9 digits if the received parameter already comes with 9 digits.. nothing should happen!

  • 1

    This type of information is important, because when I saw it I thought it was the case of "PAD" (right pad), but then it is exactly. So the important thing is to detail your question from the beginning (and the future questions also) to help us help you with your problems.

  • Blzz will edit here to add this information!

5 answers

17


Keeping the idea of doing with text does not need a loop:

let number = 18;
console.log(parseInt((number.toString() + '000000000').substring(0, 8)));
number = 678;
console.log(parseInt((number.toString() + '000000000').substring(0, 8)));

I put in the Github for future reference.

The formula used is to pick up the amount of digits you have.

If you prefer only to use mathematics (this is what I prefer since turning into text is a trick if you want a number, so I would discard the example by text, because it is very inefficient for the purpose):

let numero = 18;
console.log(numero * Math.pow(10, 8 - Math.log(numero) * Math.LOG10E + 1 | 0));
numero = 678;
console.log(numero * Math.pow(10, 8 - Math.log(numero) * Math.LOG10E + 1 | 0));

I put in the Github for future reference.

I did not make a check if the number of digits already 9, because this requirement was not in the original question and because it seems wrong or at least incomplete, then it would need to be better spelled out and if that’s all it is just put a if, nothing much.

William Nascimento made a test that shows that using only mathematics is absurdly faster. I even surprised that my code manipulating string is the second fastest (muuuito ago). I thought the padEnd() seroa faster, but it was not, this method must be very badly done, or else it is written in JS even, there would make sense he be slower. The test does not show the difference between the for and while as confronted in a response, but it should be the same. Of course it depends on each implementation, so test in multiple browsers. In my:

Resultados mostrando diferença superior a 40x para a matemática, e uma pequena porcentagem nos demais

He even did the kindness of test with Node to take away the interference that every browser offers in performance, where we can see that my code string was more than the sobro of the speed of the other forms and the mathematics gave almost 100x.

I noticed that the test can still make a bigger difference. Because the question has a numerical difference, so to do with string has to make a conversion that in the test already caught done. This conversion is nothing trivial, it is not that will increase 5% the time. The effort should almost double the total required effort, at least in some cases. Imagine then having almost 200x difference.

I realize a lot of people don’t care about that. Although this case does not happen so easily, there are cases that gives a brutal difference in cost, especially if using cloud. There is a case that can make application unfeasible, to the point that people start looking for magic solutions when it gets too slow, making the application much worse because it did not care about the performance where it mattered. I’ve had several jobs that I’ve had to solve performance issues. I never did anything great, I just saw that the previous programmer was a performance buff. In general it obtained gains that varied from tens to thousands of times, and saved the application or greatly reduced the costs, in general I spent hours or days to solve it.

If you want something short throw it into a function and use it, but don’t use something unnecessary that has such a poor performance.

  • Cool brother! I liked the alternatives! Thanks!

16

One way to do this is by using the padEnd.

The function serves exactly what you want to do. It takes as its first parameter the final amount of characters that a String must have and the character set that will fill the String to the end.

let number = 18;
let stringNumber = number.toString();
let newStringNumber = stringNumber.padEnd(9, '0');

console.log(parseInt(newStringNumber));

  • 1

    I voted +1, however it is valid to say that the complete "pad" only, does not limit, finally it is necessary to add a substring anyway, because according to the need of the author (okay that he, the author of the question, forgot to detail) can not pass 9 digits, but still the answer is worth as an extra tip if someone else gets here.

  • 1

    But it was not clear how much the AP wants if the number already has more than 9 digits.

  • 1

    That’s exactly what I said, the author forgot to detail, that’s why I didn’t even answer the question and just commented https://answall.com/questions/432376/completar-n%C3%bamero-com-zeros-at%C3%A9-que-o-tamanho-total-be-9-javascript/432380? noredirect=1#comment836983_432376, because the question was ambiguous, the fault lies with the author of the question, but in these cases of ambiguity it is better to confirm first with a comment requesting details, because in the beginning ;)

  • 1

    I noticed that your comment is related to this. Maybe your second comment lacks a nay. But even with it I still do not know what should happen if the number received has more than 9 digits.

-1

how are you?

I believe this is another way

function completar(num) {
    // Transformar em String antes de interar consome muito menos processamento.
    let number = String(num); 
    //Usar o while é mais eficiente nesse caso
    while(number.length < 9) { number += '0'; }

    return parseInt(number);
}

console.log(completar(678));

Good luck

  • 2

    Far from me wanting to criticize, but I need to make a technical note, while it is no longer efficient, I made a benchmark to test all solutions and both in Firefox and Chrome while lost in efficiency for the others, being that what uses only substring was the most efficient indeed, can test in your browser through the link: https://jsbench.me/g0k5s97920/ - any doubt can "drip" (write here @guilherme) ;)

  • 1

    @Guilhermenascimento disregarding mathematics, right? Because this is the most absurdly efficient option. You can put in my answer?

  • 1

    @Maniero can add directly if you want, or talk about commenting there? In the summary I think it is more efficient to be working the string, if it were mathematical operations only probably the result would be different even, but when it comes to manipulating "objects" it is very likely that most native Apis solve a little faster.

  • 1

    @Guilhermenascimento so surprised me the padend be worse than the substring, the while I was sure it would be worse, pity that did not compare with the for, but in theory it is to give the same thing on average

  • 1

    @Maniero probably padEnd is something poorly implemented or has a number of internal rules and/or evaluations that are necessary and we don’t have any. I made a local benchmark, with Node.js, just for the record, in this case Math was incredibly superior: https://pastebin.com/raw/Rb11cT2U - followed by substring. Vale remembers that Node.js uses the V8 and could not compare the Firefox engine standalone, if I remember well it has a great efficiency with calculations, surpassed the V8

  • 1

    @Guilhermenascimento gave it to me in the browser: https://i.stack.Imgur.com/JT7TS.png In FF all strings were a little better than in Edge, but math was much worse. In Chrome were the worst results at all, but math was not much worse.

  • 1

    @Maniero can be my impression, now I had the same result as yours, in the other tests I changed tab, maybe it is some resource management browser, but it may have been that I looked wrong at the time (despite having tested on 2 browsers)

Show 2 more comments

-1

Post has already been solved but I’ll leave a tip here for the new who search, there is a feature in javascript that allows to do this job easily.

string.padEnd(9, '0')

Any string that does not contain the 9 characters it will fill at the end of it with the digit 0.

useful links:

Developer Mozilla Padend

Developer Mozilla Padstart

-3

Not the ideal solution, but...

var boilerplate = "000000000000000000"
var numero = 23

var boilerplate = numero + boilerplate.substring(numero.toString().length, boilerplate.length);
console.log(boilerplate)

  • Does not answer the case..! =/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.