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.
In JSP you can do this using the JSTL tag <fmt:formatNumber>
. You can set either a pettern
(#0.##
) or maxFractionDigits="2"
Avoid using Java code in JSPs - use JSTL instead. See this tutorial. And see this question
You can use a DecimalFormat
to format the value as a string, e.g.:
DecimalFormat df = new DecimalFormat("#0.00");
(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 DecimalFormat
constructors directly. Instead, the recommended practice is to call one of the factory methods of NumberFormat
, then customize the pattern as needed, e.g.:
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
Javadoc including examples:
This should work in your JSP page:
<%@ page import="java.text.NumberFormat" %>
<%
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
%>
[...]
<p> the value of AB is <%= nf.format(obj.getValue()) %> <p>
Also see Bozho's answer for a way to achieve the same result using JSTL.
To answer your last question first - you should modify the JSP page, since you want to change how the number is displayed, not what the number actually is.
To do this, instead of invoking the number's default toString method, you could use a DecimalFormat object to convert the number to text in whatever format you want. In this case, you probably want to use:
new DecimalFormat("#0.##")
as the format string.
However, as per Bozho's answer there is a JSTL tag to achieve this, which is a better way to solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With