cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Add Leading Zeros

dwhansen-cbg
Contributor

I have strings that are storing a two digit number (i.e. 00, 01, 02, etc) but I need to add another leading zero (i.e. 000, 001, 002). I donโ€™t want to simply concatenate a 0 on the front in case I have values that end up being three digits.

1 ACCEPTED SOLUTION

dwhansen-cbg
Contributor

Thank you @tstack! That worked!

View solution in original post

10 REPLIES 10

dwhansen-cbg
Contributor

Thank you @tstack! That worked!

endor_force
New Contributor III

Here is an alternative solution if you need something that works for any value.
Example with padding with six zeros:
I have chosen to store the padding value in pipeline params as pad6 = "000000"

$value.toString().length < 6 ? _pad6.substring(0, _pad6.length - $value.toString().length) + $value.toString() : $value.toString()

Note that there is a .repeat() method on strings that you can use to generate these types of strings.

endor_force
New Contributor III

Thanks @tstack
So this would be an alternative solution:

$value.toString().length < 6 ? '0'.repeat(6 - $value.toString().length) + $value : $value

It feels a more sleek than my existing padding ๐Ÿ™‚

FWIW, I saw @dwhansen-cbg 's post this morning, and my immediate go-to answer was algorithmically identical to yours! Thoughโ€ฆ Iโ€™m much more of a C++ guy so your JavaScript was a lot more sleek than what I had in mind! ๐Ÿ˜†