Bash script: specify bc output number format

前端 未结 6 1543
北荒
北荒 2020-12-03 15:26

Greetings!

I uses to make some calculations in my script. For example:

bc
scale=6
1/2
.500000

For further usage

6条回答
  •  悲&欢浪女
    2020-12-03 15:47

    Just do all your calculations and output in awk:

    float_scale=6
    result=$(awk -v scale=$floatscale 'BEGIN { printf "%.*f\n", scale, 1/2 }')
    

    As an alternative, if you'd prefer to use bc and not use AWK alone or with 'bc', Bash's printf supports floating point numbers even though the rest of Bash doesn't.

    result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
    result=$(printf '%*.*f' 0 "$float_scale" "$result")
    

    The second line above could instead be:

    printf -v $result '%*.*f' 0 "$float_scale" "$result"
    

    Which works kind of like sprintf would and doesn't create a subshell.

提交回复
热议问题