Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 534
Ivan Avatar asked Nov 15 '11 03:11

Ivan


People also ask

How do you add a leading zero to a string in Java?

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.

How do you add leading zeros to a string in Python?

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.


1 Answers

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")
like image 141
huynhjl Avatar answered Sep 23 '22 11:09

huynhjl