Hello, I need to convert an integer to a string and in turn define a certain length of characters for the number, in case the length is less than it is filled with zeros on the left, an example
324 -> 00324 // suponiendo que haya definido en 5 la longitud
In python there was a specific function that did this called zfill
>>> '234'.zfill(5)
00234
Is there any equivalent in javascript or how would it be a function that does the same.
Cheers
Thinking about the logic of the Python function, I made this function, which receives as parameters your number and the desired width (the length, as you defined in your question).
If the width is less than or equal to the length of the number string, the number is returned.
Otherwise, X zeros are placed before the number, where X is the difference between the width given as a parameter and the length of the number string.
Additionally, and replicating what happens in the Python function, this function contemplates the case of using the function on a negative number. To do this, it works with absolute values, so that, if your number is negative, the sign is added
-
to the beginning of the string, the zeros that are going to be added or not, and the absolute value of the number at the end.Well you can use this:
Simple function found from this answer on SOen :
Update:
As of * ES2017 we can use the string.padStart() method
And with string.padEnd() we get the same thing but to the right of the target.
* See compatibility
function of a line. receives 2 parameters number: the number to complete with zeros on the left len: the size of the desired string
the function takes the string "0" and repeats it, to repeat it takes the len variable and subtracts from it the length of the number we want to complete, and thus creates the necessary zeros and concatenates the number passed by parameter.
To make it similar to the use in Python you could do this function:
to convert a number to String it would be:
To add leading zeros it would be:
I leave something simpler in case someone has the same problem.
To convert the integer to a string you can use the "toString()" function, and to add leading zeros "padStart" or "padEnd" in case you need them to the right.