Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script: specify bc output number format

Tags:

bash

format

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?

like image 925
Andrey Kazak Avatar asked Jun 03 '10 11:06

Andrey Kazak


3 Answers

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.

like image 117
Dennis Williamson Avatar answered Oct 20 '22 20:10

Dennis Williamson


In one line:

printf "%0.6f\n" $(bc -q <<< scale=6\;1/2)
like image 36
nad2000 Avatar answered Oct 20 '22 21:10

nad2000


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;
like image 37
janmoesen Avatar answered Oct 20 '22 21:10

janmoesen