Five Stars

Left-Padding Integer With Zeroes

I have an integer field in tMap, which may have integers from 1 to 100, for example. How can I output a 4-character string field with zeroes on the left?  For example, the integer '1' would be '0001'.  The integer '100' would be '0100'.
Thanks in advance,
HL
Fort Myers, FL
4 REPLIES
Seventeen Stars

Re: Left-Padding Integer With Zeroes


  /**
     * formats the number
     * 
     * {Category} NumberUtil
     * 
     * {talendTypes} String
     * 
     * {param} Integer(1234) number: number to format
     * {param} Integer(6) lengthWithLeadingZeros: length with leading zeros
     * 
     * {example} numberToString(1234, 6) result: 001,234
     * 
     */
public static String numberToString(Integer number, int lengthWithLeadingZeros) {
if (number != null) {
String s = String.valueOf(number);
String rawString = s.replace(".", "").replace(",", "");
System.out.println(rawString);
if (lengthWithLeadingZeros > rawString.length()) {
 StringBuilder sb = new StringBuilder();
 for (int i = rawString.length(); i < lengthWithLeadingZeros; i++) {
 sb.append('0');
 }
 sb.append(s);
 return sb.toString();
} else {
 return s;
}
} else {
return "";
}
}

Create a routine called e.g. NumberUtil and add this method.
Call this in an expression like:

Numberutil.numberToString(row1.my_int_value, 9)


this will fill the integer to a string length of 9 with the necessary zeros.
One Star

Re: Left-Padding Integer With Zeroes

Hi-
use below expression in Tmap if ur column is string.
StringHandling.RIGHT(("0000"+row1.columnname ),4).
Regards-
Raghav K
Five Stars

Re: Left-Padding Integer With Zeroes

or, finally, you can use
String.format("%04d", row1.myNumber)

if your data type is Integer rather than int, you may want to perform some null testing first, and take appropriate action.
Six Stars

Re: Left-Padding Integer With Zeroes

Apache Commons make this easy
org.apache.commons.lang.StringUtils.leftPad(nationalRegisterNumber, 11, '0')