Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set decimals to only 2 digits in Doubles? [duplicate]

Tags:

java

android

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

like image 313
theJava Avatar asked Dec 18 '25 19:12

theJava


2 Answers

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

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

you forget to add the .

like image 190
Blackbelt Avatar answered Dec 20 '25 09:12

Blackbelt


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.

like image 34
Reimeus Avatar answered Dec 20 '25 09:12

Reimeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!