Search code examples
javastringstring-formattingstringbuilder

Keep leading zeros when converted from long to string


I am converting a long to a String using String.format(). It works fine when numbers >0 are passed, but when I add leading zeros to the number, I get a different number in output. My requirement is to show user with leading zeros when leading zeros are passed. Please advise.

public class CreateContractNumber {
  public static void main(String[] args) {
    long account = 0000123;
    long schedule = 001;
    CreateContractNumber ccn = new CreateContractNumber();
    System.out.println("CONTRACT #: "+ccn.createContNbr(account, schedule));
  }

  private String createContNbr(long account, long schedule) {
    StringBuilder sb = new StringBuilder();
    sb.append(String.format("%07d", account);
    sb.append("-");
    sb.append(String.format("%03d", schedule);
    return sb.toString();
  }
}

Actual Output: CONTRACT #: 0000083-001

Expected Output: CONTRACT #: 0000123-001


Solution

  • long account = 0000123; is an octal number. 0123 oct is 83 dec which makes your output correct. If you need 123 dec just write long account = 123; as leading zeros have no effect on the value stored in long.