I am trying to decimal format a group of numbers into a 2D array and I keep getting an Error in Netbeans. It says where I have the d.format(0.0); that I need a double and have a String when then input present is 0.0. This is driving me insane and I have tried parsing just to try something and hasn't worked.

NumberFormat d = new DecimalFormat("#0.00");
    String [] counties = {"Broward", "Miami-Dade", "Palm Beach", "Average"};
    String [] petrol_type = {"Regular", "Plus-2", "Supreme", "Diesel","Average"};
    double [][] array = new double[5][4];

    public PetrolPrice (double [][] p)
    {


        for (int i = 0; i < 5; i++)
        {
            for(int j = 0; j < 4; j++) 
            {
                array[i][j] = d.format(0.0);
            }
        }

        for (int i = 0; i < 4; i++)
        {
            for(int j = 0; j < 3; j++) 
            {
                array[i][j] = p[i][j];
            }
        }
    }

That's because format returns a string. A double does not have a format - only a value. If you want to store formatted numbers, you need to store them in an array of strings. If you just want to store doubles, simply use 0.0 rather than d.format(0.0).

Ok I see what you are saying. I need to do calculations so it is easier for me to hold them as doubles. But when I do display them I need them with 2 decimal places. Any suggestions?

Store them as doubles, perform the calculations and when you're done use format when you print the results.

For displaying you can also use the printf method instead of print or println. That allows you to format data while you are printing it.

you should NEVER convert from floating point to anything else except for display purposes (or when another output vector requires another format, in which case you probably didn't want to use floating point numbers in the first place).
This to prevent losing precision in conversion, and ending up with compound rounding errors.

This article has been dead for over six months. Start a new discussion instead.