Ok so I have a database colum 'UnitPrice' with a range of values example: 23, 23.5, 43.23
Now I need to know if there is a way to format them all to the 00.00 format when printing them out. I've been failing at this for about an hour now...
Ok so I have a database colum 'UnitPrice' with a range of values example: 23, 23.5, 43.23
Now I need to know if there is a way to format them all to the 00.00 format when printing them out. I've been failing at this for about an hour now...
Simply do this:
DecimalFormat decimalFormat = new DecimalFormat("00.00");
Double[] array = new Double[] {23d, 23.5d, 43.23d};
for (int i = 0; i < array.length; i++) {
System.out.println(decimalFormat.format(array[i]));
}
or using format/printf syntax:
Double[] array = new Double[] {23d, 23.5d, 43.23d};
for (int i = 0; i < array.length; i++) {
System.out.format("%05.2f\n", array[i]);
}
You normally use the JSTL fmt
taglib for this. This way you don't need to hassle with this in the business layer, but in the view layer, there where it belongs.
To install JSTL, just drop jstl-1.2.jar in /WEB-INF/lib
and to use the fmt
taglib, just declare it in top of JSP as per its documentation.
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
Then you can use fmt:formatNumber
to format the doubles the way you want, here's an example with euro:
<p>The price is: <fmt:formatNumber value="${unit.price}" type="currency" currencySymbol="€" />