124

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

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
Ivan
  • 63,011
  • 101
  • 250
  • 382

8 Answers8

265

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")
Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219
huynhjl
  • 41,520
  • 14
  • 105
  • 158
  • 6
    Ben, dhg, thanks for the upvotes, you guys are a tough crowd though! I think we can still learn something from the other answers, and the voting system takes care of which answer is relevant. – huynhjl Nov 15 '11 at 17:24
  • 8
    you don't need to be this explicit, you can write `f"$a%07d"` (if you have a `val`/`var` `a` in scope). – fommil Jul 11 '13 at 21:22
  • 1
    @fommil, indeed, that wasn't there yet when I posted the initial answer, but I would also use the f interpolator now that it exists. – huynhjl Aug 08 '13 at 13:11
  • If you want **leading *spaces*** instead of *leading zeros* then you can use `regex` `string.replaceAll("\\G0", " ")` to replace leading zeros with spaces as told [here](https://stackoverflow.com/a/3341868/3679900) – y2k-shubham Apr 28 '18 at 04:22
  • 1
    If you want **leading spaces** instead of *leading zeros* then use `"% 7d".format(123)`. – Erik van Oosten Jan 25 '19 at 10:11
50

Short answer:

"1234".reverse.padTo(7, '0').reverse

Long answer:

Scala StringOps (which contains a nice set of methods that Scala string objects have because of implicit conversions) has a padTo method, which appends a certain amount of characters to your string. For example:

"aloha".padTo(10,'a')

Will return "alohaaaaaa". Note the element type of a String is a Char, hence the single quotes around the 'a'.

Your problem is a bit different since you need to prepend characters instead of appending them. That's why you need to reverse the string, append the fill-up characters (you would be prepending them now since the string is reversed), and then reverse the whole thing again to get the final result.

Hope this helps!

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232
34

The padding is denoted by %02d for 0 to be prefixed to make the length 2:

scala> val i = 9 
i: Int = 9

scala> val paddedVal = f"${num}%02d"
paddedVal: String = 09

scala> println(paddedVal)             
09
atiquratik
  • 1,296
  • 3
  • 27
  • 34
maxmithun
  • 1,089
  • 9
  • 18
10

huynhjl beat me to the right answer, so here's an alternative:

"0000000" + 123 takeRight 7
Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
  • This will fail for numbers greater than 10M: `"0000000" + Int.MaxValue takeRight 7` => `7483647`. While "technically" correct by the literal interpretation of the question, it's unlikely that the reader doesn't want the padded number to extend beyond 7 digits if the number is that large. – Emil Lundberg Feb 15 '17 at 15:38
  • Well you could say this solution is better because at least the digits are still correctly aligned in that particular case, unlike the accepted solution. The whole point of the question is to make the digits align properly. – Luigi Plinge Feb 16 '17 at 23:58
7
def leftPad(s: String, len: Int, elem: Char): String = {
 elem.toString * (len - s.length()) + s
}
zeromem
  • 381
  • 1
  • 3
  • 12
2

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
som-snytt
  • 39,429
  • 2
  • 47
  • 129
1

Do you need to deal with negative numbers? If not, I would just do

def str(i: Int) = (i % 10000000 + 10000000).toString.substring(1)

or

def str(i: Int) = { val f = "000000" + i; f.substring(f.length() - 7) }

Otherwise, you can use NumberFormat:

val nf = java.text.NumberFormat.getIntegerInstance(java.util.Locale.US)
nf.setMinimumIntegerDigits(7)
nf.setGroupingUsed(false)
nf.format(-123)
0__
  • 66,707
  • 21
  • 171
  • 266
0

For String use:

def completeTo10Digits(entity: String): String = {
    val zerosToAdd = (1 to (10 - entity.length)).map(_ => "0").mkString
    zerosToAdd + entity
  }