How To Turn Number To String With Padded Space or Zeroes

This article will show us how to turn numbers into the String with padded space or numbers.

Introduction

I have been recently doing code review on other developer pull-request when I found the piece of code below:

private static final String DOCUMENT_VERSION = "document_version-";

public String getDocumentVersion(int version) {
    String documentVersion = "";
    if (version > 999) {
        throw new IllegalStateException("Version number " + version + " is too large.");
    } else if (version > 99) {
        documentVersion += version;
    } else if (version > 9) {
        documentVersion += "0" + version;
    } else {
        documentVersion += "00" + version;
    }

    return "DOCUMENT_VERSION_" + documentVersion;
}

As you can immediately see, the code is bad and can be surely rewritten to something more simple. Creating a string from a number can not be so declarative, right? There needs to be a simpler way how to do it. And surely it can. Like many other general-purpose programming languages, Java has multiple libraries and functions for processing text. String class itself has a static method format() which can be fully utilized on the text changes like this.

Java String format()

The Java String class format() method returns the formatted string. Let’s look little bit on parameters of format() method.

String.format() signature

There are two type of String format() method:

public static String format(String format, Object... args)

and

public static String format(Locale locale, String format, Object... args)  

Therefore, method parameters are described as:

  • locale is specifies the locale to be applied on the format() method.
  • format is format of the string.
  • args represent arguments for the format string. It may be zero or more.

format() method returns new String. However, it is also good to be prepared for possibility of two unchecked exception:

  • NullPointerException is thrown if format is null.
  • IllegalFormatException is thrown if format is illegal or incompatible.

String.format() internal implementation

In reality, String.format() method allows usage of multiple Object arguments because internal implementation use nothing else than new instance of Formatter class.

public static String format(String format, Object... args) {
    return new Formatter().format(format, args).toString();
}

Usage of quiet Formatter class explains why we can take multiple arguments depending on the number of elements we want to format inside the string. Formatter class can use several different option of “%” character combination in order to define string formatting. In the table below are all options explained:

Formatter Argument Data Type Output
%a %A floating point (except BigDecimal) Returns Hex output of floating point number.
%b Any type “true” if non-null, “false” if null
%c character Unicode character
%d integer (incl. byte, short, int, long, bigint) Decimal Integer
%e floating point decimal number in scientific notation
%f floating point decimal number
%g floating point decimal number, possibly in scientific notation depending on the precision and value.
%h any type Hex String of value from hashCode() method.
%n none Platform-specific line separator.
%o integer (incl. byte, short, int, long, bigint) Octal number
%s any type String value
%t Date/Time (incl. long, Calendar, Date and TemporalAccessor) %t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%x integer (incl. byte, short, int, long, bigint) Hex string.

format() examples

Let us show you few tricks with format()

System.out.println(String.format("%d", 100)); // Integer
System.out.println(String.format("%s", "Anna Smith")); // String
System.out.println(String.format("%f", 42.42)); // Float
System.out.println(String.format("%x", 100)); // Hexadecimal
System.out.println(String.format("%c", 'a')); // Char
System.out.println("-----");
System.out.println(String.format("number with text: %d", 100)); // number with other text
System.out.println(String.format("%f", 42.12345)); // prints floating number
System.out.println(String.format("%10.10f", 42.12345)); // prints 10 digits for fractions padded with 0
System.out.println("-----");
System.out.println(String.format("|<-%10d->|", 222)); // Align right, padding with empty space
System.out.println(String.format("|<-%-10d->|", 555)); // Align left, padding with empty space
System.out.println(String.format("|<-% d->|", 777)); // Single space between % and conversion type is allowed
System.out.println(String.format("|<-%010d->|", 999)); // Filling space with zeros
100
Anna Smith
42.420000
64
a
-----
number with text: 100
42.123450
42.1234500000
-----
|<-       222->|
|<-555       ->|
|<- 777->|
|<-0000000999->|

Using format() to turn number into formatted string

To take for first exemplary code from code review, all what we needed to do in getDocumentVersion() method was to place custom format of string into the String class format method.

private static final String DOCUMENT_VERSION = "document_version-";

public String getDocumentVersion(int version) {
    return String.format(DOCUMENT_VERSION + "%03d", revisionNumber);
}

If we place number 1 into the method getDocumentVersion() we will get the same result as boilerplate code from code review:

Output

document_version-001

We can still quickly write some custom code to test our beliefs. But be thorough and do not forget edge cases as zero and negative numbers.

System.out.println(String.format("%03d", 999));
System.out.println(String.format("%03d", 99));
System.out.println(String.format("%03d", 9));
System.out.println(String.format("%03d", 0));
System.out.println(String.format("%03d", -9));
999
099
009
000
-09

As you can notice format() takes negative number into account its length with minus sign.

Note : If you have any crazy idea how to use format() method, let us know in comments below.

Conclusion

This article showed us how to turn a number into a string with a specific length where additional space is padded.

Did you find the String.format() method useful? Do you have your trick, or do you know another way how to turn a number into a string of specific length? Let us know in the comments below the article. We would like to hear your ideas and stories.

This entry was posted in Tips & tricks and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.