Reputation: 80769
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>
I get a compile error:
`identifier' expected but `"' found
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.
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.
I have tried a variety of alternatives including using the static Java String formatting method...
@String.format("%.2f", variable.getAverage())
...which gave
Overloaded method value [format] cannot be applied to (String, Double)
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.
Upvotes: 2
Views: 4326
Reputation: 3908
Only solution I found to properly change user's language and apply formatting to numbers is:
In Controller:
public Result lang(String lang) {
changeLang(lang);
Logger.debug("Language change request: " + lang);
return redirect(routes.Dashboard.dashboard());
}
In template we use following:
<td>@("%.2f".formatLocal(lang().toLocale(), variable.getAverage()))</td>
Upvotes: 0
Reputation: 3441
Use brackets:
@("%.2f".format(variable.getAverage()))
or:
@{
"%.2f".format(variable.getAverage())
//more scala code
}
which allows you to write multi-statement scala code in template.
Upvotes: 12
Reputation: 80769
I have found an answer, but it doesn't directly address the question at hand. I can get the String.format
code to work if I box the double
into a java.lang.Double
like this...
@String.format("%.2f", new java.lang.Double(variable.getAverage()))
This solves my problem for now, but doesn't really answer the question. There must be a Scala/Play solution... mustn't there?
Upvotes: 0