awkroundingdecimal-point

Rounding to 2 decimal points on a specific column


I have a list like this:

Cond1 4 0.2343
Cond2 10 1.765
Cond3 8 1.9234

I am trying to round the value in the 3rd column to 2 decimal points, so that it will look like this:

Cond1 4 0.24
Cond2 10 1.77
Cond3 8 1.92

I know that there is a way to do this in awk, but I can't seem to figure it out.


Solution

  • Use %.2f modifier for printf or sprintf():

    $ awk '{printf "%s %s %.2f\n",$1,$2,$3}' file
    

    or

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

    Output:

    Cond1 4 0.23
    Cond2 10 1.76
    Cond3 8 1.92
    

    More, for example, here:

    https://www.gnu.org/software/gawk/manual/html_node/Format-Modifiers.html