Awk floating-point rounding

I have a b.xyz as file,

-19.794325 -23.350704 -9.552335
-20.313872 -23.948248 -8.924463
-18.810708 -23.571757 -9.494047
-20.048543 -23.660052 -10.478968

I want to limit each entry to three decimal places.

I tried this one

awk '{ $1=sprintf("%.3f",$1)} {$2=sprintf("%.3f",$2)} {$3=sprintf("%.3f",$3)} {print $1, $2, $3}' b.xyz

it works for three columns, but how to expand it to apply to n / all columns?

+4
source share
1 answer

If you always have three fields, you can use:

$ awk '{printf "%.3f %.3f %.3f\n", $1, $2, $3}' file
-19.794 -23.351 -9.552
-20.314 -23.948 -8.924
-18.811 -23.572 -9.494
-20.049 -23.660 -10.479

For an undefined row count you can do:

$ awk '{for (i=1; i<=NF; i++) printf "%.3f%s", $i, (i==NF?"\n":" ")}' file
-19.794 -23.351 -9.552
-20.314 -23.948 -8.924
-18.811 -23.572 -9.494
-20.049 -23.660 -10.479

He will iterate over all fields and print them. (i==NF?"\n":" ")prints a new line when the last element is reached.

Or even ( thanks Jotne! ):

awk '{for (i=1; i<=NF; i++) printf "%.3f %s", $i, (i==NF?RS:FS)}' file

Example

$ cat a
-19.794325 -23.350704 -9.552335 2.13423 23 23223.23 23.23442
-20.313872 -23.948248 -8.924463
-18.810708 -23.571757 -9.494047
-20.048543 -23.660052 -10.478968

$ awk '{for (i=1; i<=NF; i++) printf "%.3f %s", $i, (i==NF?"\n":" ")}' a
-19.794 -23.351 -9.552  2.134  23.000  23223.230  23.234 
-20.314 -23.948 -8.924 
-18.811 -23.572 -9.494 
-20.049 -23.660 -10.479 

$ awk '{for (i=1; i<=NF; i++) printf "%.3f %s", $i, (i==NF?RS:FS)}' a
-19.794  -23.351  -9.552  2.134  23.000  23223.230  23.234 
-20.314  -23.948  -8.924 
-18.811  -23.572  -9.494 
-20.049  -23.660  -10.479
+8
source

Source: https://habr.com/ru/post/1531010/


All Articles