javArc
javArc

Reputation: 315

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

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

Upvotes: 4

Views: 2885

Answers (3)

krock
krock

Reputation: 29629

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

Upvotes: 0

BalusC
BalusC

Reputation: 1109272

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;" />

Upvotes: 2

fastcodejava
fastcodejava

Reputation: 41117

You need to use format api in jdk.

Upvotes: 1

Related Questions