简体   繁体   English

将 bash 数组中的每个元素转换为 x 个有效数字

[英]convert every element in bash array to x number of significant digits

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:但是,如果我在 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?如何将数组中的所有值转换为具有 x 个有效数字/浮点值? For example, if I wanted everything to have 2 significant digits, the output would be:例如,如果我希望所有内容都有 2 个有效数字,则输出将是:

echo ${new_array1}
-82.53 -82.51 -82.48 -82.49 -82.52 -82.53 -82.50 -82.48

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似乎不是一个数组,因为要查看数组中的所有元素,您必须使用echo "${array1[@]}" ${array1} prints just the first element of an array, if it is one. ${array1}只打印数组的第一个元素,如果它是一个。

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM