Formatting to three decimal on system.print with arrays

54 views Asked by At

Trying to format so that my values from the xValue and yValue arrays appear with three decimal places. This is my attempt although java seems to not be accepting it :(

    double[] xValues = new double[arrayAmount];
    double[] yValues = new double[arrayAmount];

    xValues[0] = minimumValue;

    System.out.println("Values");
           for (int index = 0; index<arrayAmount; index++)
    {

        yValues[index] = 20.0 * Math.abs((Math.sin(xValues[index])));

System.out.printf("x: " + (%1.3f, xValues[index]) + "," + "y: " + (%1.3f, yValues[index]); // compiler error


        xValues[index+1] = xValues[index] + increment;



    }
2

There are 2 answers

2
Reimeus On BEST ANSWER

printf expects a String as its first argument, your current argument is a badly formed expression. You could do

System.out.printf("x: %1.3f, y: %1.3f%n",  xValues[index], yValues[index]);
0
Boris the Spider On

You can use the String.format as suggested by @Reimeus or you can use a MessageFormat:

final MessageFormat mf = new MessageFormat("x: {0,number,0.00}, y: {1,number,0.00}");

Usage would be:

System.out.println(mf.format(new Object[]{xValues[index], yValues[index]}));