2016-01-09 134 views
3
val height = 1.9d 
val name = "James" 
println(f"$name%s is $height%2.2f meters tall") // James is 1.90 meters tall 

我在Better String formatting in Scala和Scala文档中都看到过这个例子。斯卡拉字符串格式化

%2后代表什么?我假设2f表示小数点后两位。

+0

这里阅读更多的细节 - http://docs.scala-lang.org/overviews/core/string-interpolation html的 – tuxdna

回答

3

斯卡拉string interpolation formats幕后实际使用java's Formatter

格式字符串具有以下格式:

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

在你的情况下,格式字符串使用float转换(将f末)

所以你的格式字符串要求一个浮动转换的宽度为2,精度为2

以同样的方式%4.10f将请求一个宽度为的浮点转换,精度为10

  • 传递1.9d到格式字符串%4.10f将导致字符串 1,9000000000
  • 传递1.9d到格式字符串%10.4f将导致该串中在     1,9000(它将被填充为10与空白的宽度)
1

第一个2表示您希望在输出中打印的最少字符数,第二个2表示在t之后的数字位数他需要小数点。

假设你改为“%5.2f”,并且“身高”为1.2, 它会导致' 1.20'(在开始处有空格)[不是引号;他们在这里是为了清晰]

文档分别称为宽度和精度(%[宽度]。[精度])。

http://docs.scala-lang.org/overviews/core/string-interpolation.html (这指向文档为Java格式化)

https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html