how to convert an integer to packed decimal in java

can some one help to provide sample code for converting integer to packed decimal
rishirajmAsked:
Who is Participating?
 
rishirajmConnect With a Mentor Author Commented:
Thanks CEHJ for your quick response. I was able to find solution at http://sourceforge.net/projects/zdecimal
0
 
fsze88Commented:
like this?
       System.out.println(get4DigitsFormat(4.323443));
        System.out.println(get4DigitsFormat(4.320));
        System.out.println(get4DigitsFormat(4));

    public  String get4DigitsFormat(double num) {
//        String format = "###,##0.0000";
        String format = "###,##0.####";
        DecimalFormat formatter = new DecimalFormat(format);
        num = (num == -0) ? Math.abs(num) : num; // to change -0 to 0
        return formatter.format(num);
    }
0
 
rishirajmAuthor Commented:
I need a logic to convert an integer to packed decimal format. please follow the url 'http://www.3480-3590-data-conversion.com/article-packed-fields.html' for packed decimal. thanks
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
CEHJCommented:
You might try the Microfocus COBOL library or JRecord:

http://jrecord.sourceforge.net/JRecord04.html#Header_10
0
 
rishirajmAuthor Commented:
I do not have to work with cobol file, however I need to convert an integer defined in java to packed decimal.
 
0
 
fsze88Commented:
to simply way to using DecimalFormat and store the values into String object
0
 
CEHJCommented:
>>I do not have to work with cobol file

You'll still probably be able to use the source
0
 
CEHJCommented:
Try something like the following:
    public static int intToPackedDecimal(int val) {
        int result = 0xC;
        String sVal = Integer.toString(val);
        if (sVal.charAt(0) == '-') {
            sVal = sVal.substring(1);
            result = 0xD;
        }
        final int NYBBLE = 4;
        int nybbleIndex = 1;
        for(int i = sVal.length() -1;i >= 0;i--) {
            result |= ((sVal.charAt(i) - '0') & 0xF) << (NYBBLE * nybbleIndex++);
        }
        return result;
    }

Open in new window

0
 
CEHJCommented:
That's good, now you have two - as you can see mine works ;-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.