C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The formatted() method can be called on any object—so we can use it on an Int, Double or String value.
Argument: We pass a special format string to the formatted method. This uses the same format as String.format in Java.
Scala program that uses formatted
val number = 10
// Use formatted on an Int to use the Int in a format string.
val result = number.formatted("There are %d cats.")
println(result)
Output
There are 10 cats.
Scala program that uses format
// An example format string.
val f = "I have %d dogs that weigh on average %f pounds."
// An Int and Double for the format string.
val count = 4
val averageWeight = 14.5
// Call format on the format string and print the result.
val result = f.format(count, averageWeight)
println(result)
Output
I have 4 dogs that weigh on average 14.500000 pounds.
Note: The "%1" and "%2" codes refer to the first and second arguments passed to the format method.
Java: The format method accepts the same format codes as the Java String.format method.
Scala program that uses padding format
val lefts = List(10, 200, 3000)
val rights = List("cat", "fish", "elephant")
// Loop over indexes.
for (i <- 0.until(lefts.length)) {
// Get element from each list at this index.
val left = lefts(i)
val right = rights(i)
// Use this format string.
val padding = "%1$-10s %2$10s"
// Call format to apply padding.
val result = padding.format(left, right)
println(result)
}
Output
10 cat
200 fish
3000 elephant
And: The second argument to format, "cat," is repeated twice. The first argument "frog" is inserted after the second.
Scala program that reorders, repeats values
// Specify the second argument is placed first.
// ... We can reorder and repeat arguments.
val result = "%2$s %1$s %2$s".format("frog", "cat")
println(result)
Output
cat frog cat