How can I pad an integer with zeros on the left?

后端 未结 16 2287
南旧
南旧 2020-11-21 06:31

How do you left pad an int with zeros when converting to a String in java?

I\'m basically looking to pad out integers up to 9999

16条回答
  •  难免孤独
    2020-11-21 06:59

    You can use Google Guava:

    Maven:

    
         guava
         com.google.guava
         14.0.1
    
    

    Sample code:

    String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
    String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
    

    Note:

    Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc

    Ref: GuavaExplained

提交回复
热议问题