且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 Int 转换为给定长度的字符串,前导零对齐?

更新时间:2022-06-08 23:43:00

Java 库已经相当不错了(和优秀一样)数字格式支持,可从 StringOps 丰富的字符串类:

The Java library has pretty good (as in excellent) number formatting support which is accessible from StringOps enriched String class:

scala> "%07d".format(123)
res5: String = 0000123

scala> "%07d".formatLocal(java.util.Locale.US, 123)
res6: String = 0000123

编辑 Scala 2.10 后:按照 fommil 的建议,从 2.10 开始,还有一个格式化字符串插值器(不支持本地化):

Edit post Scala 2.10: as suggested by fommil, from 2.10 on, there is also a formatting string interpolator (does not support localisation):

val expr = 123
f"$expr%07d"
f"${expr}%07d"

2019 年 4 月

  • 如果您想要前导空格而不是零,只需从格式说明符中省略 0.在上述情况下,它将是 f"$expr%7d".在 2.12.8 REPL 中测试.无需按照评论中的建议进行字符串替换,甚至无需按照另一条评论中的建议在 7 前面放置一个明确的空格.
  • 如果长度可变,s"%${len}d".format("123")
  • If you want leading spaces, and not zero, just leave out the 0 from the format specifier. In the above case, it'd be f"$expr%7d".Tested in 2.12.8 REPL. No need to do the string replacement as suggested in a comment, or even put an explicit space in front of 7 as suggested in another comment.
  • If the length is variable, s"%${len}d".format("123")