How to Use Java.String.Format in Scala

How to use java.String.format in Scala?

While all the previous responses are correct, they're all in Java. Here's a Scala example:

val placeholder = "Hello %s, isn't %s cool?"
val formatted = placeholder.format("Ivan", "Scala")

I also have a blog post about making format like Python's % operator that might be useful.

How to use String.format() in scala

Declare dd elements as type Int and this should work.

val dd = new Array[Int](3)
. . . //unchanged
String.format("%04d-%02d-%02d",dd:_*)

Or ...

"%04d-%02d-%02d".format(dd:_*)

Scala - how to format a collection into a String?

The specific error is due to the fact that you pass a Seq[String] to format which expects Any*. You only pass one parameter instead of five. The error says it doesn't find an argument for your second format string.

You want to apply the pattern on every metric, not all the metrics on the pattern.
The paddings in the format string are too big for what you want to achieve.

    val pattern = "%-2s | %-5s | %-4s | %-6s"
metrics.map(m => pattern.format(m.makeCustomMetric: _*))
.mkString("Id | Name | Rate | Value\n", "\n", "\nId | Name | Rate | Value")

The _* tells the compiler that you want to pass a list as variable length argument.
makeCustomMetric should return only the List then, instead of a string.

def makeCustomMetric: String = Seq(id, name, rate, value)

What is the best way to format a string in Scala?

I was simply using it wrong. Correct usage is .format(parem1, parem2).

How to combine String format with Arrays/Lists?

Turn each element into a String of the desired format before the mkString.

Seq(23,5,111,7).map(n => f"$n%4d").mkString
//res0: String = " 23 5 111 7"

Or, alternatively, you might construct a single format String and then format() the collection.

val nums = Array(1, 22, 3, 444)
("%4d" * nums.length).format(nums:_*)
//res1: String = " 1 22 3 444"

Better String formatting in Scala

In Scala 2.10 you can use string interpolation.

val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall") // James is 1.90 meters tall

How to repeat argument in String format in Scala

This should work:

"%1$s-%1$s-%1$s" format "OK"

The format method of WrappedString uses java.util.Formatter under the hood. And the the Formatter Javadoc says:

The format specifiers for general, character, and numeric types have the following syntax:

%[argument_index$][flags][width][.precision]conversion

The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.



Related Topics



Leave a reply



Submit