Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding floating number using AWK

Tags:

printf

awk

I have a file b.xyz as,

-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 of the entries to three decimal digits.

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 for n/all columns?

like image 604
user3311147 Avatar asked Mar 10 '14 17:03

user3311147


1 Answers

If you will always have three fields, then 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 number of lines, 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

It will loop through all the fields and print them. (i==NF?"\n":" ") prints a new line when the last item 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
like image 101
fedorqui 'SO stop harming' Avatar answered Dec 28 '22 00:12

fedorqui 'SO stop harming'