Left-Padding Integer With Zeroes

Six 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
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')
Four Stars

Re: Left-Padding Integer With Zeroes

for integer  datatype...how to write right paded with space

Spoiler
 

15TH OCTOBER, COUNTY HALL, LONDON

Join us at the Community Lounge.

Register Now

2019 GARNER MAGIC QUADRANT FOR DATA INTEGRATION TOOL

Talend named a Leader.

Get your copy

OPEN STUDIO FOR DATA INTEGRATION

Kickstart your first data integration and ETL projects.

Download now

What’s New for Talend Summer ’19

Watch the recorded webinar!

Watch Now

Best Practices for Using Context Variables with Talend – Part 4

Pick up some tips and tricks with Context Variables

Blog

How Media Organizations Achieved Success with Data Integration

Learn how media organizations have achieved success with Data Integration

Read

6 Ways to Start Utilizing Machine Learning with Amazon We Services and Talend

Look at6 ways to start utilizing Machine Learning with Amazon We Services and Talend

Blog