How to build a fixed-length string representing an integer

Hi,
I would like know how can I use the API to get a String representing an int with fixed length. I mean, I would like something similar to Integer.parseInt(), but I need to set the length of that String in such a way that, for instance, if I need the String to be 5 character long, and the int is 37, the String would be 00037
Thanks in advance and best regards,
Miguel ?ngel

I wrote pad() methods in my string helper that can be used for this purpose.
In particular, you want to prepad with '0' to a length of 5:
com.Ostermiller.StringHelper.prePad(Integer.toString(37), 5, '0');
http://ostermiller.org/utils/StringHelper.html

Similar Messages

  • A better way of building the fixed-length String

    I created the following code to build a fixed length string. I checked other posts for the same topic, but I found mine is better. The code below converts a double numeric value to a fixed length string with padding of white spaces (or other types):
    Line 15 initializes the char array to while space; line 13 creates a character array; lines 17, 18 copy the array created in line 13 to the one initialized in line 15.
    Any comment is welcomed.
    1. import java.text.*;
    2.
    3. public class jformat {
    4.
    5. public static void main(String[] args) {
    6.
    7. char[] fb=new char[14];
    8. char[] tb;
    9. int c, f;
    10. DecimalFormat fmt=new DecimalFormat("########0.00");
    11. double dbl=12345.66;
    12.
    13. tb=fmt.format(dbl).toCharArray();
    14.
    15. for(c=0; c<fb.length; c++) fb[c]=' ';// this line is not required in JDK 1.5
    16.
    17. for(c=tb.length-1, f=fb.length-1; c>=0; c--, f--){
    18.     fb[f]=tb[c];
    19. }
    20. System.out.println(new String(fb));
    21.
    22. }
    23.
    24. }

    Here's a couple of alternatives. One uses a StringBuffer and the second, for Java 5 only, uses the Formatter capabilities.
    import java.text.DecimalFormat;
    public class jformat
        public static void main(String[] args)
            int fieldSize = 14;
            double dbl = 12345.66;
            String dblString = new DecimalFormat("0.00").format(dbl);
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < fieldSize - dblString.length(); j++)
                sb = sb.append(' ');
            System.out.println(sb.append(dblString).toString());
             *  The above code works in Java versions 1.3, 1.4, and 1.5.
             *  However, 1.5 provides the Formatter class, and the single
             *  line below can replace the preceeding code.
            System.out.printf("%14.2f%n", dbl);
    }

  • ABPA  code to compress table into a table of fixed-length strings

    Hi all,
    I need to compress a large, sparse table into a table of fixed-length strings in my ABAP code, and then uncompress it.  Is there a standard format or facility to do this?  I seem to remember a function that does this, but any other hints would be appreciated.
    Thank you in advance,
    Sunny

    For example, given a table like:
    Column0    Column1    Column2
    abc            C               !@#&@
                     P
    def                              $*(
    Compress it into a table consisting of one column of fixed-length strings, like:
    Column0
    0abc1C2
    !@#&@01
    P20def1
    2$*(
    ..and then uncompress it back out to the original table.
    Sunny

  • How to map xml to a fixed length string?

    Hi All,
    I have a requirement to map request xml to a string of fixed length and format:
    For eg,
    Source:
    <Person>
    <Name>George</Name>
    <Age>21</Age>
    </Person>
    Target:
    String of format
    Name : 8 chars
    Age : 2chars.
    so the required mapping should result in
    "George 21".
    Note: 2 blanks after "George" to allow for 8 characters. Is this kind of mapping possible using ALSB xquery? I have tried to create a MFL representation for the string , and used it in the xquery as the targer but it is generating
    "George21".Only data present in source is getting mapped :(

    My advice would be to use MFL transformation for that.
    Documentation about MFL can be found at edocs: http://edocs.bea.com/alsb/docs26/fbhelp/index.html
    Find tips and tricks about ALSB at my blog: http://dev2dev.bea.com/blog/jordinho/

  • How to handle a fixed length file without newline?

    Hi Experts,
    I'd like to handle a fixed length file without newline by sender file adapter.
    A file like following.
    It contains three recores."AAXBBBXCCCCX" is one record.
    AA1BBB1CCCC1AA2BBB2CCCC2AA3BBB3CCCC3
    I tried that following two parameters set. But only first recored was read.
    fieldFixedLengths
    fieldFixedLengthType
    Please tell me how to handle.
    Thanks
    Shinya Kawagoe.

    For this case we wrote a simple Adapter Module inserting an end of line character after an offset.
    This way it can be reused in many interfaces.
    And reading the whole file may not be an option in case of large source files. May cause performance / memory issues.
    eolbean.offset = <recordLlen>
    XMLPayload xmlpayload = msg.getDocument();
    byte[] content = xmlpayload.getContent();
    byte crlf = 0x0A;
    int current = 0;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int lines = content.length / recordLen;
    do
         lines--;
         baos.write(content, current, recordLen);
         if (lines > 0) // if other lines, eol required
              baos.write(crlf);
              current += recordLen;
    } while (lines > 0);
    xmlpayload.setContent(baos.toByteArray());
    baos.close();
    Audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS,     MODULE + " Done EOLing.");

  • Fixed Length Strings.

    Hi ,
       I have to download a longtext from SAP.
       The length of the longtext has to be fixed 5000 ie...Even if the length of the longtext from SAP is 1000 remaining 4000 spaces should get appended.
      I am moving the long text into a variable l_line which I have declared in the following way L_LINE(5000).
       But after moving the longtext into this variable it still shows the actual length of the longtext whereas I need 5000 fixed length.
      How to solve it.
    Thanks,

    Hi Renu Raj,
    Just WRITE the LONG TEXT again in to the variable with RIGHT
    JUSTIFIED. It will prefixes SPACEs and STRLEN will return 5000.
    i.e. as follows,
      WRITE : L_LINE TO L_LINE RIGHT-JUSTIFIED.
      CNT_LEN = STRLEN( L_LINE ).
    Now the CNT_LEn will have '5000'.
    While you process the LONG TEXT, just CONDENSE it and go ahead. It will remove LEADING SPACEs.
    i.e. as follows,
      CONDENSE L_LINE.
      CNT_LEN = STRLEN( L_LINE ).
    Now CNT_LEN will have an actual length.
    Regards,
    R.Nagarajan.
    We can -

  • How to create a fixed length file

    Can anyone suggest a simple technique for creating fixed
    length files? CSV and delimited files are pretty simple using
    CFFILE. Is there an elegant way to create fixed length
    files?

    Simplest: Use LJustify() or RJustify() on your lines of data.
    EG:
    <cfset FileLine = RJustify (LineOfText, 128)>

  • How to output non-fixed length field by DMEE?

    Hi,
    In DMEE, I need to set a fixed length for each field. If the source data length is less than what we set, it will ouput space to fill in rest of the place. Is that a way I could just out put exactly what I need? No extra space to be output.
    Thank you!

    Hi
    The extra spaces can be removed as follows:
    In the transaction DMEE --> Head --> Format attributes --> Field type = 1
    Best regards
    Jean Daniel

  • How to store a varying length string in the database

    Hi,
    what is the best way to store a string (which can be infinitely long) in the database?
    there's limitation on varchar2...can i use blobs/clobs ??
    Thanks in advance for any enlightenment!
    null

    Is this a JDBC question?
    Meta data solutions mean that you will only find problems at runtime that would be obvious at compile time with a non-metadata solution. Code generation makes production of large numbers of these easy.
    But if you want metadata then you create a seperate class in a seperate package which holds the constants. The specifics depend on the implementation but you will typically have one class for each 'type' that is supported.
    That package is used by both the server and the client code.
    You can of course put other common functionality in the package (like a wrappers for the collections themselves, validation of names, etc.)

  • How to build a library of string functions?

    I want to create a set of my own special string functions. Trouble is I cannot create a class that extends String because it has been declared final. I want to be able to use the existing String functions as well as my own. Any ideas?
    Thanks in advance.

    Create a class that doesn't extend String. Use the String methods. You don't have to extend a class to use its methods. Example:public class LameUtility {
      public static char getFirstCharacter(String s) {
        return s.charAt(0);
    }

  • How to Convert the Stream of strings into ArrayList Integer

    I have a String st = "12 54 456 76ASD 243 646"
    what I want to do is print it like this from the ArrayList<Integer>:
    12
    54
    456
    243
    646
    It should catch the "76ASD" exception as it contain String Character.
    This is how I am doing, which it seems to work but when it reaches the 76ASD it catches the exception so it is not adding the rest to the Arraylist, therefore I could not print in sequence.
      public static void main(String[] args) {
            // TODO code application logic here
            getDatas(testString);
            for (int i = 0; i < at.size(); ++i) {
                System.out.println(at.get(i));
        private static ArrayList<Integer> getDatas(String aString) {
            StringTokenizer st = new StringTokenizer(aString);
            try {
                while (st.hasMoreTokens()) {
                    String sts = "";
                    sts = st.nextToken();
                    at.add(Integer.parseInt(sts));
            } catch (Exception e) {
                System.out.println("Error: " + e);
            return at;
        }Please guide me where I am going
    Thanks

    paulcw wrote:
    This is one of the few cases where I'd say catching an exception as part of the design is acceptable. When parsing, either something parses, or it doesn't. Using parseInt, we're parsing the string and using the result of the parse. By using a regular expression, we're parsing it twice, in two different ways, which may get out of sync. Not only that, if you have a more complicated case, like negative numbers and decimals, the regex gets really ugly.
    I agree this is exactly the case where it is appropriate to try, catch, handle, move on. I sometimes wish there were an Integer.isValid(String) method, but even if there were, we'd call it, and if it returned true, we'd then call parseInt anyway, which would repeat the same work that isValid did. All it would buy us would be an if test instead of a try/catch.

  • Fixed-length numbers and strings

    Hello,
    I have to make a critical decision about API usage. I would be grateful if some of you could share their experiences. This will help me make an informed decision and avoid potential trouble further down the line.
    I have to use fixed-length integer numbers and fixed-length strings such as for example:
    -A string that is exactly 5-letter long (no longer and no shorter than 5 letters). e.g. "abcde"
    -A number that is exactly 8-digit long (no longer and no shorter than 8 digits). e.g. "12345678"
    Ideally I would get some sort of exception when the "container" for the letters or digits contains less or more than what the spec says.
    I am not sure which classes or primitives could meet my needs. As far as the fixed-length string is concerned I initially thought of using a array of chars but an array of chars is not that easy to manipulate and contains "garbage" until you explicitely fill it in with data. I'd rather some sort of class.
    Can anyone please advise me?
    Thanks in advance,
    Julien.

    Why not use the same thing like in the case of the String
    /**Warning: this is an example and not very good design.*/
    public class FixedInteger {
       private int min, max;
       private int value;
       public int getValue() { return value;}
       public void setValue(int v) {
            if (v >= min && v < max) {
                throw new Exception();
            value = v;
       /**ex. min = 10000, max = 100000 for 5 digit numbers*/
       public FixedInteger(int min, int max, int value) {
           this.min = min; this.max = max;
           setValue(value);
    }You can do tricks like convert it to immutabla like the String and Integer class in the Java Api
    Edited by: szgy on Oct 5, 2007 2:22 PM

  • Fixed Length File attachment to Mail Receiver

    Hi,
    I have an interface requirement IDOC - PI - Fixed Length File attached to email.
    Is it possible to do this? I need to pass the IDOC through a mapping and content conversion to build the fixed length file, I then need to attach this file to an email and send it to a user.
    Any help would be greatly appreciated.
    Thanks
    Gareth

    Hi,
    I actually need to convert the IDOC to a different file format before sending it on. Eg.
    <IDOC>
         <Segment 1...n>
               <username>User</username>
               <address>Address 1</Address>
         </Segment>
         <Segment>
               <username>User2</username>
               <address>Address 2</Address>
         </Segment>
    <IDOC>
    Converted to flat file with structure:
    User......Address 1.....
    User2....Address 2.....
    The file needs to have fields of Fixed Length (thats what the .... after each field is to represent)
    So I think the Data Type I am using for the file needs to go through Content Conversion to do this change, and then the file attached to an email.
    I hope this makes sense.

  • Splitting a string when an integer is reached

    Hi,
    I'm trying to figure out how, if possible, to split a string when an integer comes in the strong. What I'm doing is reading from a web page and the output is "1930Stella" as an example. What I want to do is insert those into a table, so it's like this:
    String     |     Integer
    Stella           1930I'm not sure how I can go about doing this, please help!

    YoungWinston wrote:
    aeternaly wrote:
    I'm trying to figure out how, if possible, to split a string when an integer comes in the strong. What I'm doing is reading from a web page and the output is "1930Stella" as an example.Another wrinkle for you. Could it ever be "-1930Stella"?
    WinstonNo, it can't ever be anything other than "1930Stella" or "Stella1930", but it will always be integerString in the format that I'm reading from the site.
    almightywiz wrote:
    Just a thought...
    Why not make this function return something like this:
    >
    "1930Stella" -> parseString -> "1930|Stella"
    >
    You're obviously halfway there, but right now if you want to get both the number and the string out of the input, you have to loop over the input twice. Why not just loop over the input once, insert a delimiter between your 'fields', and call split on the resulting string later? Then again, you know the overall requirements for the issue at hand.
    Also, is the input string always a number followed by characters (i.e. 1930Stella), or can it be something ridiculous like "1234abc56d7e8"? I only ask because right now your method only handles the first case nicely, on the assumption that your result will always be "number followed by characters".As I said above, the method works for what I need (only integerString/stringInteger format). I was looking at the delimiter idea but couldn't quite fully understand it. I'll give it another go, though!

  • How to get a string with fixed length

    I want to implement something like movechar() of c in java. I want to return a string which has a fixed length that contains the given string and spaces for remaining length.
    Please let me know how can I implement it.
    Thanks & Regards,
    Nasrin.n

    Do you mean padding a String?
          * This method pads the string s to size n using char c to make up for missing characters.
         public static String padString(String s, int n, char c, boolean paddingLeft) {
              StringBuffer str = new StringBuffer(s);
              int strLength = str.length();
              if (n > 0 && n > strLength) {
                   for (int i = 0; i <= n; i++) {
                        if (paddingLeft) {
                             if (i < n - strLength) str.insert(0, c);
                        else {
                             if (i > strLength) str.append(c);
              return str.toString();
         }

Maybe you are looking for

  • Rejeição: NF-e de devolução não possui documento fiscal referenciado

    Após go live para o novo layout 3.10 da NF-e, nos deparamos com um situação de rejeição 321 - Rejeição: NF-e de devolução não possui documento fiscal referenciado nos documentos de devolução de clientes(NFD) lançadas na VL01. Esses documentos são ref

  • Error while creating application

    Hi, I am getting the following error while creating the application. "IHspAppAssistantACM_SaveAppAssistant() Error Unable to Create application FirstApp. Error Number: 2147024891" No other application is existing with this name. I checked the HspEven

  • Suppress XML Structure view

    Hi,       May  I know the SuppressedWidgetID to hide the XML structure view? IsStructureViewShowing=kFalse; I need to hide XML Structure view. Kindly advise me. Regards Senthil Kumar V

  • Plugin reference library to ms crm 2011/2013/2015.

    Plugin reference library to ms crm 2011/2013/2015. Eg:like for jscript http://garethtuckercrm.com/2011/03/16/jscript-reference-for-microsoft-dynamics-crm-2011/ Please help me

  • Job and dates

    Hi, How could I submit a job that executes every day at 12:00:00AM ? Thanks!