Bash script: specify bc output number format

Hello!

I use bc to do some calculations in my script. For instance:

bc
scale=6
1/2
.500000

For further use in my script, I need "0.500000" set to ".500000".

Could you help me customize the bc output format for my case?

+5
source share
6 answers

In one line:

printf "%0.6f\n" $(bc -q <<< scale=6\;1/2)
+14
source

Quick and dirty, since it scaleapplies only to decimal digits, and bcdoes not have a sprintf-like function :

$ bc
scale = 6
result = 1 / 2
if (0 <= result && result < 1) {
    print "0"
}
print result;
+3
source

awk:

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

, bc, AWK "bc", Bash printf , Bash .

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

:

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

sprintf .

+3

, :

float_scale=6

function float_eval()
{
    local stat=0
    local result=0.0
    if [[ $# -gt 0 ]]; then
        result=$(echo "scale=$float_scale; $*" | bc -q | awk '{printf "%f\n", $0}' 2>/dev/null)
        stat=$?
        if [[ $stat -eq 0  &&  -z "$result" ]]; then stat=1; fi
    fi
    echo $result
    return $stat
}
+2
echo "scale=3;12/7" | bc -q | sed 's/^\\./0./;s/0*$//;s/\\.$//'
+2

bc ? bc ?

some_math.bc

scale=6
output=1/2
print output

, :

$ bc -q some_math.bc | awk '{printf "%08f\n", $0}'
0.500000

If I only need an output string for a null value for formatting, I would use awk.

+1
source

All Articles