0

How can I format the following to 4 decimal places. I wasn't able to use System.out.format("****") or System.out.printf("****")

System.out.println("\n Two Distinct Complex Roots Exists: root1 = " +
                    x1 + " + " + imaginary + "i and root2 = " + x2 +" - " +imaginary + "i");

here is the quadratic formula that I'm trying to format

else if (disc < 0) {
            x1 = x2 = -b / (2 * a);
            imaginary = Math.sqrt(-disc) / (2 * a);
            System.out.format("%.3f%n Two Distinct Complex Roots     Exists: root1 = " +
                    x1 + " + " + imaginary + " and root2 = " + x2 +" - " +imaginary);

        }
  • What exactly have you tried? – dan1st Oct 01 '20 at 04:46
  • System.out.printf("\n Two Distinct Complex Roots Exists: root1 = " , x1 , " + " , imaginary , " and root2 = " , x2 ," - " +imaginary); System.out.format("%.4f%n Two Distinct Complex Roots Exists: root1 = " + x1 + " + " + imaginary + " and root2 = " + x2 +" - " +imaginary); – sinco demayo Oct 01 '20 at 04:50
  • How to use printf: `System.out.printf("text with e.g. %.4f where numbers should be placed or similar",numbers);` – dan1st Oct 01 '20 at 04:53
  • I have actually looked through a lot of similar problems and try to use them, but since I have multiple variables it starts giving me errors. – sinco demayo Oct 01 '20 at 04:55

1 Answers1

2
DecimalFormat df = new DecimalFormat("#.####");

System.out.println(df.format(d));
Mikalai Lushchytski
  • 1,563
  • 1
  • 9
  • 18