Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control of display the number of digit in JSP?

Tags:

java

jsp

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.

like image 827
Questions Avatar asked Oct 11 '10 08:10

Questions


3 Answers

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

like image 74
Bozho Avatar answered Nov 15 '22 23:11

Bozho


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:

  • http://download-llnw.oracle.com/javase/6/docs/api/java/text/NumberFormat.html
  • http://download-llnw.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

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.

like image 24
Grodriguez Avatar answered Nov 15 '22 23:11

Grodriguez


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.

like image 30
Andrzej Doyle Avatar answered Nov 15 '22 23:11

Andrzej Doyle