In JavaScript, I need to have padding.
For example, if I have the number 9, it will be "0009". If I have a number of say 10, it will be "0010". Notice how it will always contain four digits.
One way to do this would be to subtract the number minus 4 to get the number of 0s I need to put.
Is there was a slicker way of doing this?
To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.
In JavaScript, to pad a number with leading zeros, we can use the padStart() method. The padStart() method pads the current string with another string until the resulting string reaches the given length. The padding is applied from the start of the current string.
Use the zfill() String Method to Pad a String With Zeros in Python. The zfill() method in Python takes a number specifying the desired length of the string as a parameter and adds zeros to the left of the string until it is of the desired length.
You can use the built-in String.prototype.padStart()
n = 9; String(n).padStart(4, '0'); // '0009' n = 10; String(n).padStart(4, '0'); // '0010'
Not a lot of "slick" going on so far:
function pad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; }
When you initialize an array with a number, it creates an array with the length
set to that value so that the array appears to contain that many undefined
elements. Though some Array instance methods skip array elements without values, .join()
doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a + 1
in there.
Example usage:
pad(10, 4); // 0010 pad(9, 4); // 0009 pad(123, 4); // 0123 pad(10, 4, '-'); // --10
function padToFour(number) { if (number<=9999) { number = ("000"+number).slice(-4); } return number; }
Something like that?
Bonus incomprehensible-but-slicker single-line ES6 version:
let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;
ES6isms:
let
is a block scoped variable (as opposed to var
’s functional scoping)=>
is an arrow function that among other things replaces function
and is prepended by its parametersnumber =>
)return
you can omit the braces and the return
keyword and simply use the expressionIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With