How to convert an Int to a String of a given length with leading zeros to align?

前端 未结 7 1311
醉酒成梦
醉酒成梦 2020-12-12 16:40

How can I convert an Int to a 7-character long String, so that 123 is turned into \"0000123\"?

7条回答
  •  情书的邮戳
    2020-12-12 17:33

    In case this Q&A becomes the canonical compendium,

    scala> import java.text._
    import java.text._
    
    scala> NumberFormat.getIntegerInstance.asInstanceOf[DecimalFormat]
    res0: java.text.DecimalFormat = java.text.DecimalFormat@674dc
    
    scala> .applyPattern("0000000")
    
    scala> res0.format(123)
    res2: String = 0000123
    

提交回复
热议问题