function PadDigits(input, totalDigits)
{
var result = input;
if (totalDigits > input.length)
{
for (i=0; i < (totalDigits - input.length); i++)
{
result = '0' + result;
}
}
return result;
}
But it won't make life easier. C# has a method like PadLeft and PadRight in the String class, unfortunately Javascript doesn't have this functionality build-in
I ran into much the same problem and I found a compact way to solve it. If I had to use it multiple times in my code or if I was doing it for any more than four digits, I'd use one of the other suggested solutions, but this way lets me put it all in an expression:
((x<10)?"000": (x<100)?"00": (x<1000)?"0": "") + x
It's actually the same as your code, but using the ternary operator instead of "if-else" statements (and moving the "+ x", which will always be part of the expression, outside of the conditional code).
A padded number is a string.
When you add a number to a string, it is converted to a string.
Strings has the method slice, that retuns a fixed length piece of the string.
If length is negative the returned string is sliced from the end of the string.
to test:
var num=12;
console.log(("000" + num).slice(-4)); // Will show "0012"
Of cause this only works for positive integers of up to 4 digits. A slightly more complex solution, will handle positive integers:
'0'.repeat( Math.max(4 - num.toString().length, 0)) + num
Create a string by repeat adding zeros, as long as the number of digits (length of string) is less than 4
Add the number, that is then converted to a string also.
Edit: from now on you should probably use this function:
let number = 3
let string = number.toString().padStart(3, '0')
console.log(string) // "003"
Or if only the whole part of a float should be a fixed length:
let number = 3.141
let array = number.toString().split('.')
array[0] = array[0].padStart(3, '0')
let string = array.join('.')
console.log(string) // "003.141"
Neither of these simple uses handle sign, only showing a fraction part when number is not an integer, or other scenarios - so here is a simple example formatting function without options:
function format (number) {
let [ integer, fraction = '' ] = number.toString().split('.')
let sign = ''
if (integer.startsWith('-')) {
integer = integer.slice(1)
sign = '-'
}
integer = integer.padStart(3, '0')
if (fraction) {
fraction = '.' + fraction.padEnd(6, '0')
}
let string = sign + integer + fraction
return string
}
console.log(format(3)) // "003"
console.log(format(-3)) // "-003"
console.log(format(4096)) // "4096"
console.log(format(-3.141)) // "-003.141000"
Although notably this will not handle things that are not numbers, or numbers that toString into scientific notation.