Mindr
Mindr

Reputation: 1

Formatting a double to 2 decimal places - compilation error

I'm trying to format a double to 2 decimal places in a program I'm writing.

I currently have

import java.text.DecimalFormat;
public class testd {
    double d = 1.234567;
    DecimalFormat df = new DecimalFormat("#.##"); 
    System.out.println(df.format(d));​
}

Could someone tell me where it is I'm going wrong?

This line is giving me errors:

System.out.println(df.format(d));​

Upvotes: 0

Views: 227

Answers (4)

WonderWorld
WonderWorld

Reputation: 966

For some very odd reason i am getting an illegal character: '\u200b' notification on this line:

System.out.println(df.format(d));​

after i copied and pasted your code in Netbeans, but after typing the same line myself, the error doesn't appear and is working fine.

System.out.println(df.format(d));

So my advice would be to re-enter the line without any copy/pasting from a website whatsoever.

Upvotes: 0

Viltér Panitz
Viltér Panitz

Reputation: 84

Your code is right, your problem is that you're not inside a method. I're trying to put your code in the class context.

Put inside a method and will work.

public static void main(String[] args) {
        double d = 1.234567;
        DecimalFormat df = new DecimalFormat("#.##"); 
        System.out.println(df.format(d));
    }

Upvotes: 1

Masudul
Masudul

Reputation: 21961

You need to put System.out.println into a method or in block to compile. To run you need main method.

public class Test { // class name should start with capital

 public static void main(String[] arg){
  double d = 1.234567;
  DecimalFormat df = new DecimalFormat("#.##"); 
  System.out.println(df.format(d));​
 }
}

Upvotes: 1

Joe Doe
Joe Doe

Reputation: 141

You need the main method:

public static void main(String[] args) {
    double d = 1.234567;
    DecimalFormat df = new DecimalFormat("#.##");
    System.out.println(df.format(d));
}

Upvotes: 0

Related Questions