The program outputs the roots of a quadratic equation:

System.out.printf(Locale.US, "%.4f %.4f", x2,x1); 

In addition to simple output, it also rounds the number with an accuracy of 10^-4 . But I need exactly “with accuracy”, i.e. WITHOUT CIRCULATION. How to do it?

  • Have you already done what you ask, what does not suit you? - user6550
  • @klopp, the %.4f pattern rounds ( round ) the value to 4 characters, and the vehicle wants to truncate it to 4 characters. - Nofate ♦

3 answers 3

Direct printf () from C. Here the essence is in the line% .4f% .4f ", .4f and determines the output of the number float with an accuracy of 4 decimal places. Remove or put the required number of characters

  • You do not understand me. 4f (rounding to 4 decimal places, as I understood). I also need NOT ROUNDING, but how to say that .. “chopping off” by 4 decimal places - user17711
  • Maybe I'll say something stupid, but the first thing that comes to my mind now is to take String from your number and cut off unnecessary characters after the point - Yuri_Prime

You need to round down.

 DecimalFormat df = new DecimalFormat("#.0000"); df.setRoundingMode(RoundingMode.DOWN); System.out.println(df.format(12.49688f)); System.out.println(df.format(12.456)); System.out.println(df.format(12.0)); 

will lead

 2.4968 12.456 12 

    There is another way to hack:

    1. First round up to 5 digits after comma.
    2. Then we discard the last significant digit.