2

In my response i am getting the value as 80.00000

DecimalFormat df = new DecimalFormat("##.##");
TextField.setText(df.format(Double.parseDouble(custom.getValue())));

My problem is i am getting 80.000, i am doing a parseDouble which will return a primitive double type and i am doing a format to this double to 2 decimals.

Why am i getting 80 instead of 80.00?

I changed my way and tried with this.

TextField.setText(String.format("%2f",Double.parseDouble(custom.getValue()))); 

Now i am geting 80.000000 instead of 80.00

theJava
  • 14,620
  • 45
  • 131
  • 172

4 Answers4

11

Should be "%.2f" instead of "%2f"

TextField.setText(String.format("%.2f",Double.parseDouble(custom.getValue())));

you forget to add the .

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
2

Why am i getting 80 instead of 80.00?

The first example should be:

DecimalFormat df = new DecimalFormat("##.00");

Otherwise any non significant fractional digits will be suppressed.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

java.text.NumberFormat is a good alternative

final NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
nf.setGroupingUsed(false);
System.out.println(nf.format(123456789.123456789));
cahen
  • 15,807
  • 13
  • 47
  • 78
0

Change %2f to %.2f in the String.format parameter.

Mihir Shah
  • 996
  • 10
  • 19