Jordan Jordan - 3 years ago 106
Java Question

Unexpected DecimalFormat output - Java

I'm taking my java class, and I'm working on a Tsubo calculator for my assignment. I don't usually ask questions on stack overflow so forgive me if this seems basic. I've done some searching here and tried some of the solutions but none have worked in my case. I'm going to copy just part of my conversion below

```
System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");

sqftInput = keyboard.nextInt();

// Double is converted to string so out put remains an object of the same data type

sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");


sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftResultAsString + " Tsubo"); `


When I do this, it tells me I can't format a double that the type is not applicable to arguments for DecimalFormat.

When I change it to look like this (offending line is commented out)

' System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");

sqftInput = keyboard.nextInt();

// Double is converted to string so out put remains an object of the same data type
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");


//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftFormatted + " Tsubo");


The program compiles and runs, and when I use 5238 as an input number, then my output looks like this --> 5238.0 is equal to :java.text.DecimalFormat@674dc Tsubo

instead of actually displaying the answer which is 325.07.

I've also tried using some regex formatting using the stringFormat but i wind up getting illegalformatting exception.

Long story short, What I'm trying to achieve is an output that is formatted to 2 decimal places, and then converted to a string that the system outputs as an answer. What am I missing? Is this Decimal Format automatically converting this to a string object?

Answer Source

DecimalFormat is used to produce a formatted String. If you print it directly, it will show its (kind of, it's called idenity hashcode) memory address cause that is what the DecimalFormat.toString() does.

Instead, you should use it to produce your output string and print that directly.

As follows:

 sqftResult = sqftInput / TSUBO;
        DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
        String out =  sqftFormatted.format(sqftResult); // or whatever you want to print

        //sqftResultAsString = Double.toString(sqftFormatted);
        System.out.println(sqftInput + " is equal to :" + out  + " Tsubo");

See docs for more details

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download