How do I format a string with string interpolation in Scala as a fixed width string?
Asked Answered
G

1

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?

Gastrectomy answered 13/3, 2013 at 1:6 Comment(1)
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.Gastrectomy
P
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"
Plasmosome answered 13/3, 2013 at 1:9 Comment(5)
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.Gastrectomy
Is it possible to get left-aligned formatting (padding spaces on the right hand side) with this approach?Underbid
Yes, pre-pend '-' to the width specifier: scala> f"$companyName%-15s"Plasmosome
can I make the 15 a parameter: like val w=15 and now do something like: f"$companyName%${w}s"Pointblank
@drjerry Probably the only way of achieving something like this is using String.format("%" + w + "s", w, companyName).Dimitrovo

© 2022 - 2024 — McMap. All rights reserved.