12

I'm interfacing with a really old system and the file I need to generate needs a field that is a formed from a string but needs to be exactly 15 in width.

I want something like this:

val companyName = "FooBar, Inc" // 11 chars
f"$companyName%s"

To return:

"    FooBar, Inc"

Is there a slick way to do what I'm trying to do with the String interpolation?

Daniel Werner
  • 1,350
  • 16
  • 26
myyk
  • 1,537
  • 1
  • 15
  • 35
  • This question now seems really simple, this is because I was doing something else wrong when I had the solution the whole time, so I striped down the question so it made sense. – myyk Mar 13 '13 at 01:34

1 Answers1

22

Use String.format with a format string. Surely something there will do what you want :-)

This code would do what you want:

scala> val companyName = "FooBar, Inc"
companyName: String = FooBar, Inc

scala> f"$companyName%15s"
res0: String = "    FooBar, Inc"
myyk
  • 1,537
  • 1
  • 15
  • 35
  • Oh, wow. I'm going to edit my question since it's not even correct. I don't know what I was typing into the REPL since this does clearly work. Thanks. – myyk Mar 13 '13 at 01:29
  • 1
    Is it possible to get left-aligned formatting (padding spaces on the right hand side) with this approach? – 0__ May 06 '13 at 11:39
  • 5
    Yes, pre-pend '-' to the width specifier: `scala> f"$companyName%-15s"` –  May 06 '13 at 17:40
  • 2
    can I make the 15 a parameter: like `val w=15` and now do something like: `f"$companyName%${w}s"` – dr jerry Jun 09 '17 at 14:46
  • 1
    @drjerry Probably the only way of achieving something like this is using `String.format("%" + w + "s", w, companyName)`. – Ava Jun 16 '20 at 20:07