Search code examples
javaformattingformatfilewriterprintwriter

Is there a way to format decimal point numbers while using PrintWriter, without using "Format" function in Java?


I am writing out data to a file for my Java simulation. My code looks like this:

try (PrintWriter out = new PrintWriter(new FileWriter("data/test.dat", true));)
      {
        out.print(DecimalPointData);
        out.print("\t");
        out.print(OtherData);
        out.print("\n");            
        } catch (IOException {
            e.printStackTrace();
        }

This prints out data like this:

  -1.0749999955296516   0.0
  -1.0919999964535236   0.0
  -1.0749999955296516   0.0
  -0.5339999794960022   0.0

I am aware of the fact that data in java can be formatted using .format, i.e., if I can just say

out.format("%.3f%n",DecimalPointData); 

instead of

out.print(DecimalPointData);

But I do not want to use this in my code, because when I write to the file, the columns look disoriented, my file data looks ends up looking like this:

-1.075
      0.0
-1.092
      0.0
-1.075
      0.0

Is there anything else I need to know while formatting? or Is there another way to format decimal point numbers with the use of "Format" function in java?


Solution

  • You can use a single format to write a line

    out.format("%.3f %.1f%n",DecimalPointData, OtherData); 
    

    EDIT: If you want to add a TAB in your output, use the below format string

    out.format("%.3f\t%.1f%n",DecimalPointData, OtherData);