0

I know you can alter the amount of floating points in a textfile of values with something along the lines of:

awk '{printf("%.2g",$1)}' filename.txt

which will reduce everything to two decimal digits. However, if I have a string in bash:

echo ${array1}
-82.534592 -82.511200 -82.478912 -82.490959 -82.521393 -82.529610 -82.503510 -82.478218

How do I convert all values in the array to have x number of significant digits / floating point values? For example, if I wanted everything to have 2 significant digits, the output would be:

echo ${new_array1}
-82.53 -82.51 -82.48 -82.49 -82.52 -82.53 -82.50 -82.48
WX_M
  • 458
  • 4
  • 20
  • It looks like you don't have an array, but a blank separated string. – Benjamin W. Feb 12 '20 at 19:14
  • For future reference, the values you want have 4 significant figures. The value you’re referring to is just the number of digits after the decimal point. – crdrisko Feb 12 '20 at 23:37

1 Answers1

0

Your array1 doesn't seem to be an array because to see all elements in the array, you'd have to use echo "${array1[@]}". ${array1} prints just the first element of an array, if it is one.

You can create an array like this:

array1=(-82.534592 -82.511200 -82.478912 -82.490959 -82.521393 -82.529610 -82.503510 -82.478218)

To print all elements rounded to two digits after the decimal point:

$ printf '%.2f\n' "${array1[@]}"
-82.53
-82.51
-82.48
-82.49
-82.52
-82.53
-82.50
-82.48

To read that output into a new array:

readarray -t newarray1 < <(printf '%.2f\n' "${array1[@]}")

And to inspect the new array:

$ declare -p newarray1
declare -a newarray1=([0]="-82.53" [1]="-82.51" [2]="-82.48" [3]="-82.49" [4]="-82.52" [5]="-82.53" [6]="-82.50" [7]="-82.48")
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116