I want to ask a question about the JSP and Java. I am writing the JSP page and has a bean class. In the class, i have a getter function which will return a double var in the jsp page. I used the following code to display the number.
<p> the value of AB is <%=obj.getValue() %> <p>
I expect that display will like the following
the value of AB is 0.45
However, the real display is the following
the value of AB is 0.4569877987
I only want to display the last two digit. What should I do in order to display what I want. Should I modify the JSP page or the Java class variable? thank you.
You can use a
DecimalFormatto format the value as a string, e.g.:(the pattern assumes you always want two digits in the fractional part, even if the fractional part is zero. Otherwise, use
#0.##)However in general it is recommended not to call the
DecimalFormatconstructors directly. Instead, the recommended practice is to call one of the factory methods ofNumberFormat, then customize the pattern as needed, e.g.:Javadoc including examples:
This should work in your JSP page:
Also see Bozho’s answer for a way to achieve the same result using JSTL.