How can I convert an Int
to a 7-character long String
, so that 123
is turned into "0000123"
?
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.
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:
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.s"%${len}d".format("123")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With