Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
997 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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"

Edit Apr 2019:

  • 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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...