Java format integer limiting width by truncating to the right

2.9k Views Asked by At

I know I could use String.substring or write some extra code, but is there a simple way to achieve this by only using String.format?

For example, I only want the first 6 chars "1234ab" in the result:

int v = 0x1234abcd;
String s = String.format("%06x", v) // gives me 1234abcd
String s = String.format("%06.6x", v) // gives me IllegalformatPrecesionException

The Java Formatter doc said the precision could be used to limit the overall output width, but only to certain data types.

Any ideas? Thanks.

2

There are 2 best solutions below

0
On

Depending how may hex digits you want to truncate...

You can divide by powers of 16

public static void main(String[] args) throws Exception {
    int v = 0x1234abcd;
    // This will truncate the 2 right most hex digits
    String hexV = Integer.toHexString(v / (int)Math.pow(16, 2));
    System.out.println(hexV);
}

Results:

1234ab

Even if you mess up and divide by a power of 16 that exceeds the length of your hex string, the result will just be zero.

Then there's the substring() approach

public static void main(String[] args) throws Exception {
    int v = 0x1234abcd;
    String hexV = Integer.toHexString(v);
    // This will truncate the the 2 most right hex digits 
    //   provided the length is greater than 2
    System.out.println(hexV.length() > 2 ? hexV.substring(0, hexV.length() - 2) : hexV);
}
0
On

Since you wanted to do this with just the Formatter.

Here's my result.

1234ab
  1234abcd

And here's the code.

public class Tester {

    public static void main(String[] args) {
        int v = 0x1234abcd;
        String s = String.format("%6.6s", String.format("%x", v));
        System.out.println(s);
        s = String.format("%10.10s", String.format("%x", v));
        System.out.println(s);
    }

}

I convert the hex number to a String, then truncate or left pad the String with the second Formatter.