Andrey Kazak
Andrey Kazak

Reputation: 181

Bash script: specify bc output number format

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

bc
scale=6
1/2
.500000

For further usage in my script I need "0.500000" instead of ".500000".

Could you help me please to configure bc output number format for my case?

Upvotes: 13

Views: 31569

Answers (6)

SteinAir
SteinAir

Reputation: 106

echo "scale=3;12/7" | bc -q | sed 's/^\\./0./;s/0*$//;s/\\.$//'

Upvotes: 5

nad2000
nad2000

Reputation: 4925

In one line:

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

Upvotes: 21

Dennis Williamson
Dennis Williamson

Reputation: 360325

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.

Upvotes: 5

irkenInvader
irkenInvader

Reputation: 1416

Can you put the bc usage into a little better context? What are you using the results of bc for?

Given the following in a file called some_math.bc

scale=6
output=1/2
print output

on the command line I can do the following to add a zero:

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

If I only needed the output string to have a zero for formatting purposes, I'd use awk.

Upvotes: 1

janmoesen
janmoesen

Reputation: 8020

Quick and dirty, since scale only applies to the decimal digits and bc does not seem to have a sprintf-like function:

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

Upvotes: 4

Andrey Kazak
Andrey Kazak

Reputation: 181

I believe here is modified version of the function:

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
}

Upvotes: 2

Related Questions