Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java DecimalFormat.format does not format the number?

Tags:

java

I have the method below, but for some reason it is not formatting the area to have only one decimal. All help is appreciated.

public double beraknaArea()
    {
       DecimalFormat formatter = new DecimalFormat("#0.0");
       double area = 0;
       area = radie*radie*3.14;
       formatter.format(area);
       return area;
     }
like image 511
user1534779 Avatar asked Feb 27 '26 12:02

user1534779


2 Answers

You are returning the same double, and not the output of the formatter.

The format() method does not alter the double that you pass in, it returns a String format of the double.

like image 177
Jon Lin Avatar answered Mar 01 '26 02:03

Jon Lin


No methods in Java may change the type of a declared variable, or mutate any primitive value (or indeed String). You need to return what formatter.format(area) returns, not the unchanged value of area.

public String beraknaArea()
{
   DecimalFormat formatter = new DecimalFormat("#0.0");
   double area = radie*radie*3.14;
   return formatter.format(area);
 }
like image 23
OrangeDog Avatar answered Mar 01 '26 00:03

OrangeDog



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!