Forum Discussion

dwhansen-cbg's avatar
dwhansen-cbg
Contributor
6 years ago
Solved

Add Leading Zeros

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.

10 Replies

  • evanhk's avatar
    evanhk
    New Contributor II

    (“0” + $value).slice(-3)

    .slice(-3) will take the last 3 characters in the string

    • PSAmmirata's avatar
      PSAmmirata
      Employee

      This worked well. I was padding a string with spaces. Beware that when I validated the pipeline the string in the preview data was not displayed with the padding, but the string was actually padded as expected.

  • endor_force's avatar
    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()
    
    • tstack's avatar
      tstack
      Former Employee

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

      • endor_force's avatar
        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 🙂

  • $value = “01”.
    I’ve tried $value.sprintf(“%03d”, “0”) and several other similar things but it doesn’t seem to work.

    • tstack's avatar
      tstack
      Former Employee

      It looks like the format and the value to format are switched around. The sprintf() method is to be called on the format string, like so:

      "%03d".sprintf(parseInt($value))
      

      Note that the value passed in needs to be a number and not a string, which is why I used parseInt().