The question has been answered for integers printed in decimal format, but I'm looking for an elegant way to do the same with integers in non-decimal format (like binary, octal, hex).
Creation of such Strings is easy:
String intAsString = Integer.toString(12345, 8);
would create a String with the octal represenation of the integer value 12345. But how to format it so that the String has like 10 digits, apart from calculating the number of zeros needed and assembling a new String 'by hand'.
A typical use case would be creating binary numbers with a fixed number of bits (like 16, 32, ...) where one would like to have all digits including leading zeros.
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
Zero padding is a technique typically employed to make the size of the input sequence equal to a power of two. In zero padding, you add zeros to the end of the input sequence so that the total number of samples is equal to the next higher power of two.
To display numbers with leading zeros in Java, useDecimalFormat("000000000000").
For oct and hex, it's as easy as String.format
:
assert String.format("%03x", 16) == "010";
assert String.format("%03o", 8) == "010";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With