change precision of bash variable

I have a variable in a bash script,

DISTANCE=`awk 'BEGIN {FS="\t"} {if (NR==2) print $3;}' $OUTFILE`

this is a real number taken from a file. The value are like,

0.334561754018

I am using this value in a file name,

'$NAME'_'$DISTANCE'.txt

I would like to shorten the number some to something like 0.33. I am assuming that these are strings and not numbers. There is no real need for anything like rounding if that is difficult. If I could just print the first 4 characters, or something like that, that would be a big improvement.

LMHmedchem

% printf '%.2f\n' 0.334561754018 
0.33
1 Like

Thanks, I got it to work with,

DISTANCE=`printf '%.2f' $DISTANCE`

LMHmedchem

Or you can just modify your awk command in order to produce the desired output:

DISTANCE=$(
  awk 'BEGIN { FS = "\t" } 
  NR == 2 { 
      printf "%.2f\n", $3
      }' "$OUTFILE"
  )

If for any reason that's not possible, with bash >= 3 alternatively you could use something like this:

printf -vDISTANCE '%.2f' $DISTANCE

that with the code provided, depending on the distance value, you may get a result of more than 4 character.

[ctsgnb@shell ~/sand]$ printf '%.2f\n' 1234.334561754018
1234.33
[ctsgnb@shell ~/sand]$ printf '%.4s\n' 1234.334561754018
1234
[ctsgnb@shell ~/sand]$ printf '%.4s\n' 0.334561754018
0.33
[ctsgnb@shell ~/sand]$ printf '%.4s\n' .33456175
.334
[ctsgnb@shell ~/sand]$ printf '%.2f\n' .33456175
0.33