2

I have the following code:

<s:property value="currentPrice" />
<s:property value="oldPrice" />
<span class="badge">-50%</span>

Now I want to display the percentage in the <span> tag by the formula:

percentage = (currentPrice - oldPrice) / oldPrice * 100

How can I do that in Struts2 ?

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
lenhhoxung
  • 2,530
  • 2
  • 30
  • 61

2 Answers2

2

Client side solution:

<s:property value="currentPrice" />
<s:property value="oldPrice" />
<span class="badge">
    <s:property value="%{((currentPrice - oldPrice) / oldPrice) * 100}" />%
</span>

Or in alternative,

Server side solution:

public Integer getPercentage(){
    return ((currentPrice - oldPrice) / oldPrice) * 100;
}
<s:property value="currentPrice" />
<s:property value="oldPrice" />
<span class="badge">
    <s:property value="percentage" />%
</span>
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • While I accept your answer because it provides the correct result, here is my our solution: ` %` – lenhhoxung Nov 30 '15 at 17:56
  • Actually, I'm new to Struts2 and I don't know when to use the character #. In addition, if I put your code (client side) into the getText function, it doesn't show the value. Can you help explain? – lenhhoxung Nov 30 '15 at 17:58
  • 1
    If `currentPrice` and `oldPrice` are action attributes, there is no need to use the `#`. BTW if with `I don't know when to use the character #` you mean in **OGNL**, [read this](http://stackoverflow.com/questions/8007858/whats-the-difference-between-and-signs-in-struts-tags), if instead you mean in the **getText()** pattern, [read this](http://stackoverflow.com/a/20520668/1654265). In every case, please consider **upvoting** every answer that you've found helpful, to express your appreciation for the efforts. – Andrea Ligios Nov 30 '15 at 22:40
1

You can do it using javascript like below -

var currentPrice = document.getElementById("currentPrice").value;
var oldPrice = document.getElementById("oldPrice").value;
var percentage = (currentPrice-oldPrice)/oldPrice * 100
Murli
  • 1,258
  • 9
  • 20