views:

230

answers:

5

Greetings!

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" insted of ".500000".

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

+1  A: 
janmoesen
+1 for this solution: no need to use other tools such as awk.
Hai Vu
A: 

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 "%08s\n", $0}'
0.500000

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

irkenInvader
A: 

Thank you!

Actually in my script I use function taken from here:

float_scale=6

function float_eval()
{
    local stat=0
    local result=0.0
    if [[ $# -gt 0 ]]; then
        result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
        stat=$?
        if [[ $stat -eq 0  &&  -z "$result" ]]; then stat=1; fi
    fi
    echo $result
    return $stat
}
Andrey Kazak
Could you help me to modify this function?
Andrey Kazak
Is this this answer? If not, it shouldn't be posted as one. You can edit your original question to do follow-ups or post small ones in comments attached to the appropriate post.
Dennis Williamson
A: 

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
}
Andrey Kazak
Is this the answer?
Dennis Williamson
A: 

Just do all your calculations and output in awk:

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