在Play 2模板中格式化Double的正确方法是什么 [英] What is the proper way to format a double in a Play 2 template
问题描述
这是我在Play 2模板中的缩写代码...
Here is my abbreviated code from a Play 2 template...
@(variable: com.mypackage.Variable)
<div class='statsbody'>
<div class='statsform'>
<label>Average:</label>
<span>@"%.2f".format(variable.getAverage())</span>
</div>
</div>
我收到一个编译错误:
`identifier' expected but `"' found
我从这个问题中得到了上面的想法,其中指出了如何可以在scala命令提示符下执行此操作,这很好,但是在模板中不起作用.
and I got the idea above from this question, which says how to do it at the scala command prompt, which is great, but doesn't work in a template.
getAverage()
方法属于我正在使用的外部Java程序包,它返回原始的double
.一切正常,没有格式,我可以愉快地显示正确的数字.
The getAverage()
method belongs to an external Java package I am using and it returns a raw double
. This all works fine and without the formatting I can happily display the right numbers.
我尝试了多种选择,包括使用静态Java String格式化方法...
I have tried a variety of alternatives including using the static Java String formatting method...
@String.format("%.2f", variable.getAverage())
...给了
Overloaded method value [format] cannot be applied to (String, Double)
所以我的问题是,在Play 2模板中格式化双打的正确方法是什么?我知道我可能会使用Javascript,但是我想知道是否有Play/Scala解决方案.
So my question is, what is the proper way to format a double in a Play 2 template? I know I could probably use Javascript, but I'd like to know if there's a Play/Scala solution to this.
推荐答案
使用方括号:
@("%.2f".format(variable.getAverage()))
或:
@{
"%.2f".format(variable.getAverage())
//more scala code
}
它允许您在模板中编写多语句scala代码.
which allows you to write multi-statement scala code in template.
这篇关于在Play 2模板中格式化Double的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!