Search code examples
jspjstljsp-tags

How to round the decimal value to two places using JSTL where the List is created as output from database


I'm working on small project where the the sql output (result set) is converted in to list and passed on to JSP to display the data.

How to I round a particular column contents to upto two decimal places.

Here's the code that I have so far:

Passing resultSet to create list:

rs = stmt.executeQuery(sql);
List<String> output = setData(rs);

Setting data:

public List<String> setData(ResultSet rs) throws SQLException {

     ResultSetMetaData md = rs.getMetaData();
     int columns = md.getColumnCount();
     ArrayList list = new ArrayList();
     while (rs.next()){
         HashMap row = new HashMap(columns);
         for(int i=1; i<=columns; ++i) {           
             row.put(md.getColumnName(i),rs.getObject(i));
         }
         list.add(row);
     }
     return list;
 }

Using the above code in JSP page as shown below:

<%
 String sql = "My SQL code goes here";
 ConnectionFactory cf = new ConnectionFactory();
 List<String> output = cf.getData(sql);
 pageContext.setAttribute("output",output);
%>
<tbody>
     <c:forEach items="${output}" var="ls">
         <tr>
             <td><c:out value="${ls.col1}"/></td>
             <td><c:out value="${ls.col2}"/></td>
             <td><c:out value="${ls.col3}"/></td>
             <td><c:out value="${ls.col4}"/></td>
             <td><c:out value="${ls.col5}"/></td>
         </tr>
     </c:forEach>
</tbody>

Now let's say "ls.col3" has decimal values (which unfortunately I can't restrict at SQL), how to restrict/round the decimals to two places?

Any insight is greatly appreciated :)

Regards,


Solution

  • The actual issue was in my SQL code. I have used round function which doesn't seem to be working. I have replaced that with

    to_char(calculations, 'FM999D00')

    to solve this issue.

    Thanks a ton for looking into this.