Formating a float in Java, help please!

icklejez

Member
Jan 12, 2007
50
0
0
Im trying to format a float in a JTable thats been taken from an SQL database, heres what ive got:

{
float price = results.getFloat(5);

row = new Vector();
row.addElement(new String(results.getString(1)));
row.addElement(results.getString(2));
row.addElement(results.getInt(3));
row.addElement(results.getInt(4));
row.addElement("£"+ (price));
rows.addElement(row);
}

so i've given the getFloat(5) a variable name 'price' - how do i format the float 'price' to two decimal places, like 0.00? is it some thing like:

float price.%2f = results.getFloat(5);

I cant remember, thanks!
 

Pwnbroker

Senior member
Feb 9, 2007
245
0
0
In C, you use the setw command with some other commands. I'm sure in Java it's the same. I'll break out my Java book and take a look.

Edit: come to think of it, setw is not useful in a gui environment, it's used mainly for command line output. I checked the Java book's index for setw, it doesn't exist.
 

icklejez

Member
Jan 12, 2007
50
0
0
Hmmm, im sure its some thing like:

String price = results.getFloat(5);
//float price = results.getFloat(5);
String.format("%.2f", price);

row = new Vector();
row.addElement(new String(results.getString(1)));
row.addElement(results.getString(2));
row.addElement(results.getInt(3));
row.addElement(results.getInt(4));
row.addElement("£"+ (price));
rows.addElement(row);
 

lozina

Lifer
Sep 10, 2001
11,711
8
81
I would do this:

NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.UK);
System.out.println(nf.format(price));
 

lozina

Lifer
Sep 10, 2001
11,711
8
81
or the more manual way:

NumberFormat nf2 = NumberFormat.getInstance();
nf2.setMaximumFractionDigits(2);
System.out.println("$"+nf2.format(price));