JSTL Round off/down number

14,336

This (below) should be the only safe way to do it. pattern="##" is not well supported, minIntegerDigits="2" is easier and cleaner.

<c:set var="minutes" value="${fn:substringBefore(seconds div 60, '.')}"/> 
<fmt:formatNumber var="seconds" minIntegerDigits="2" value="${ seconds - (minutes*60) }"/>
Share:
14,336
user1386375
Author by

user1386375

Updated on June 04, 2022

Comments

  • user1386375
    user1386375 almost 2 years

    This might be a dumb question, but let's say I have a variable seconds in my JSP page and its value is 779. Now I want to convert it into minutes and seconds by doing the following:

        <c:set var="${seconds / 60}" value="min"/>
        <c:set var="${seconds mod 60}" value="sec">
    

    This way I get min = 12.983333 and sec = 59.0.

    Now I want to merge the two and display the result as 12:59. The problem I am facing is that min keeps getting rounded up to 13. I have tried many things, such as:

        <fmt:parseNumber var="minutes" integerOnly="true" type="number" value="${min}" />
    
        <fmt:formatNumber type="number" pattern="###" value="${min}" var="minutes" />
    
        fn:substringBefore(min, '.')
    
        maxFractionDigits="0"
    
        // and so on...
    

    But all of them just return 13 consistently. I am a bit clueless at this point. But I may have missed something. I hope someone here has an idea, or a hint, about what might be wrong.

    -edit

    The code below made it work in the end. I have no clue what was wrong, since its also working with "/" now. Maybe some minor mistake elsewhere. Nevertheless thanks a lot for your time :) Kudos!

        <c:set var="min" value="${fn:substringBefore((seconds div 60), '.')}"/>  
        <fmt:formatNumber var="sec" pattern="##" value="${seconds mod 60)}"/>   
    
  • Ankur
    Ankur about 11 years
    Hi, this doesn't work for me, <c:set var="min" value="${29 div 10}" /> gives me 2.9
  • asgs
    asgs over 7 years
    fn:substringBefore is the way to go. Thanks!