Reputation: 194
val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall") // James is 1.90 meters tall
I've seen this example both at Better String formatting in Scala and in the Scala docs.
What does the 2 after % stand for? I assume the 2f means two decimal places.
Upvotes: 3
Views: 1141
Reputation: 21595
Scala string interpolation formats actually use java's Formatter behind the scenes .
The format string has the following format :
%[argument_index$][flags][width][.precision]conversion
In your case the format string is using a float
conversion ( the f
at the end)
So your format string is asking for a float conversion with a width of 2
and a precision of 2
In the same way %4.10f
would request a float conversion with a width of 4
and a precision of 10
.
1.9d
to the format String %4.10f
would result in the string
1,9000000000
1.9d
to the format String %10.4f
would result in the string
1,9000
(it would be padded to a width of 10 with whitespace)Upvotes: 3
Reputation: 1633
The first 2 indicates the minimum number of characters that you want printed in the output, and second 2 would indicate the number of digits after the decimal point that you need.
Suppose you instead had "%5.2f", and the 'height' was 1.2,
it would result in ' 1.20'
(with the space in the beginning) [not the quotes; they are here for clarity]
The docs refer to them as Width and Precision respectively (%[width].[precision]).
http://docs.scala-lang.org/overviews/core/string-interpolation.html (this points to the docs for the java Formatter)
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
Upvotes: 1