Can't format my numbers to 3 decimal points (.000)

429 Views Asked by At
public class SimpleTrig {
    public static void main(String[] args) {

        DecimalFormat dx;
        dx = new DecimalFormat("0.000");

        String angleStr;
        double angle, angleCosine;

        angleStr = JOptionPane.showInputDialog(null,"Enter an angle (in degrees)");
        angle = Double.parseDouble(angleStr);
        angleCosine = Math.cos(Math.toRadians(angle));

        JOptionPane.showMessageDialog(null, "The cosine of " + angle 
                                      + " degrees is " + dx.format(angleCosine));
    }
}

The output of angleCosine is giving me an output of 0.000 as my final answer regardless of any angle I input.

6

There are 6 best solutions below

1
On

Use new DecimalFormat("#.###")

0
On

Change

 dx = new DecimalFormat("0.000");

into

 dx = new DecimalFormat("#0.000");

Or

 dx = new DecimalFormat("#.###");
0
On

You can use something like

DecimalFormat df2 = new DecimalFormat( "#0.00" );
0
On

try to change the format to

DecimalFormat dx = new DecimalFormat("#.000");
0
On

Seems to work fine when I run it, enter 45, get 0.707. using java 1.6.0_30

Had to add final closing bracket and package definition to get it to run.

0
On

Try Using

  DecimalFormat dx = new DecimalFormat("##,##0.000");

or Check angleCosine value is proper.