Search code examples
julianumber-formatting

How to save array or matrix in Julia with specific format?


I've tried to use Julia and I have some question for fixing length of float and decimal point when saving data.

The input file's name is "L100_A100_C100.dat" and it has data as below:

SIMULATION RESULTS
 0.599566E+00 0.666925E-06   0.3348E+02   0.2527E+03  -0.6948E+04  
 0.599633E+00 0.666924E-06   0.3394E+02   0.2529E+03  -0.6949E+04  
 0.599699E+00 0.666922E-06   0.3424E+02   0.2528E+03  -0.6949E+04  
 0.599766E+00 0.666920E-06   0.3440E+02   0.2527E+03  -0.6949E+04  
 0.599833E+00 0.666919E-06   0.3460E+02   0.2525E+03  -0.6948E+04  
 0.599899E+00 0.666919E-06   0.3488E+02   0.2522E+03  -0.6948E+04  
 0.599966E+00 0.666919E-06   0.3530E+02   0.2520E+03  -0.6948E+04  

So I programmed as below:

file = open("L100_A100_C100.dat", "r")
data = readdlm(file, Float64, skipstart=1)
writedlm("output.txt", data)

and Output is

0.599566    6.66925e-7  33.48   252.7   -6948.0
0.599633    6.66924e-7  33.94   252.9   -6949.0
0.599699    6.66922e-7  34.24   252.8   -6949.0
0.599766    6.6692e-7   34.4    252.7   -6949.0
0.599833    6.66919e-7  34.6    252.5   -6948.0
0.599899    6.66919e-7  34.88   252.2   -6948.0
0.599966    6.66919e-7  35.3    252.0   -6948.0

but my question is how to fix length of float and decimal point (just like '%10.3f' in Python)?


Solution

  • In Julia, printf is available as a macro. A Julia macro is a piece of Julia code that generates other Julia code at compile time. In this case, at the compile time, the macro @sprintf generates a formatting object (this also validate the formatting string) and the formatting code. Later, at the runtime, the actual formatting is performed.

    Hence you can do:

    julia> x = rand(2,3)
    2×3 Matrix{Float64}:
     0.475864  0.285398  0.969636
     0.46037   0.708167  0.45792
    
    julia> using Printf
    
    julia> m = (a->(@sprintf "%10.3f" a)).(x)
    2×3 Matrix{String}:
     "     0.476"  "     0.285"  "     0.970"
     "     0.460"  "     0.708"  "     0.458"
    

    Now you have a matrix of pre-formatted texts that you directly dump to file (I use stdout instead):

    julia> writedlm(stdout, m, "" , quotes=false)
         0.476     0.285     0.970
         0.460     0.708     0.458