PDA

Click to See Complete Forum and Search --> : String/Number formatting


x-ice
Mar 27th, 2008, 05:56 AM
How can I format a number in java so that only two numbers are displayed after the decimal point?

I have tried using DecimalFormat with no luck.

Here is the code I used. float newTotPrice = totPrice + Double.valueOf(myProduct.getPrice()).floatValue();
//For formatting a number
DecimalFormat df = new DecimalFormat("#.00");
//Format 'newTotPrice' so that only two digits are shown after the decimal point
df.format(newTotPrice);
//Show total price
lblTotPrice.setText("£ " + newTotPrice); This doesn't work as I got a result of "£ 509.97003"

ComputerJy
Mar 27th, 2008, 10:26 AM
import java.text.DecimalFormat;
import java.text.NumberFormat;


public class Util {

public static void main(String[] args) {
double d = 10.45;
NumberFormat formatter = DecimalFormat.getNumberInstance();
formatter.setMaximumFractionDigits(2);
System.out.println(formatter.format(Math.PI));
}
}

x-ice
Mar 27th, 2008, 11:40 AM
When the number of more than 999 the formatter seems to put a comma in. How can I set it so that it doesn't do this?

E.g. 1,023.23 should be 1023.23

x-ice
Mar 27th, 2008, 11:49 AM
formatter.setGroupingUsed(false);