awk if condition match and fix print decimal place

Hi All,
I have problem in the middle of implementing to users, whereby the complaint is all about the decimal place which is too long. I need two decimal places only, but the outcome from command is always fixed to 6.
See the sample :
before:

Sort Total
      Site    Sort  SortName   Parts   %/Total
----------------------------------------------
               9                1    0.06
              10               6    0.35

using command:

awk '$1 ==    10 {$2-=1;$3=$2/1720*100} 1' inputfile|sed 's/^10 /               10               /g'

result:

Sort Total
      Site    Sort  SortName   Parts   %/Total
----------------------------------------------
               9                1    0.06
              10               5 0.290698

The thing is, I need the 0.290698 above to just have 2 decimal places, become --> 0.29
THks !

Desire result:

Sort Total
      Site    Sort  SortName   Parts   %/Total
----------------------------------------------
               9                1    0.06
              10               5    0.29

Hello horsepwoer,

Could you please try following and let us know if this helps.

awk '$1 ==    10 {$2-=1;$3=$2/1720*100;printf "\t\t%d\t\t%d    %.2f\n",$1, $2, $3;next} 1'  Input_file

Thanks,
R. Singh

1 Like

Try:

awk '$1==10{$2--; $3=$2/17.2} 1' CONVFMT="%7.2f" file | sed 's/^10 /               10              /g'

or

awk '$1==10{sub($2 "[ \t]*" $3, sprintf("%d %7.2f", --$2, $2/17.2))}1' file

or

awk '$1==10{$2--; $3=$2/17.2; printf "%16d %15d %7.2f\n", $1, $2, $3; next}1'  file
1 Like

Thks guys, all the example above is working fantastically !
At the end i insert this "CONVFMT="%7.2f"" into the command, and it works perfectly :slight_smile: