开发者

Need to format a set of float variables to 00.00

Ok so I have a database colum 'UnitPrice' with a range of values example: 23, 23.5, 43.23

开发者_StackOverflow

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...


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="&euro;" />


You need to use format api in jdk.


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]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜