What is the correct way to format the double in the Play 2 template

Here is my shorthand code from the 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 am getting compile error:

`identifier' expected but `"' found

      

and I got the above idea from this question which says how to do it on the scala command line, which is great, but doesn't work in a template.

The method getAverage()

belongs to an external Java package I am using and returns raw double

. This all works great and without formatting I can happily display the correct numbers.

I've tried various alternatives including using Java's static 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 correct way to format the double in the Play 2 template? I know I could use Javascript, but I would like to know if there is a Play / Scala solution for this.

+2


source to share


3 answers


Use brackets:

@("%.2f".format(variable.getAverage()))

      

or



@{
  "%.2f".format(variable.getAverage())
  //more scala code
}

      

which allows you to write multi-valued scala code in a template.

+11


source


I found an answer, but it doesn't directly address the question. I can get the code String.format

to work if I paste double

in java.lang.Double

like this ...

@String.format("%.2f", new java.lang.Double(variable.getAverage()))

      



Now this solves my problem, but doesn't really answer the question. There should be a Scala / Play solution ... shouldn't there be?

0


source


Only solution I found to change the user's language correctly and apply formatting to the numbers:

In the controller:

public Result lang(String lang) {
    changeLang(lang);
    Logger.debug("Language change request: " + lang);
    return redirect(routes.Dashboard.dashboard());
}

      

We use the following in the template:

 <td>@("%.2f".formatLocal(lang().toLocale(), variable.getAverage()))</td>

      

0


source







All Articles