I have a large number and I want to make bc calculation. Example:
T_Mab = 6.00899e+09
and I wanna print it like this:
echo 'T_Mab = '${T_Mab}' [s] = '${T_Mab}/31557600' [year]' | bc -l
It is giving me "syntax error". So how can I do it?
I have a large number and I want to make bc calculation. Example:
T_Mab = 6.00899e+09
and I wanna print it like this:
echo 'T_Mab = '${T_Mab}' [s] = '${T_Mab}/31557600' [year]' | bc -l
It is giving me "syntax error". So how can I do it?
You cannot just write whatever you want to display and dump them to bc
. Another issue is that bc
does not accept scientific notations. Check [How to get bc to handle numbers in scientific (aka exponential) notation? for details.
Assuming that the number is already converted to the correct form as in the answers in the linked question, you can write it like this in bash
.
T_Mab=6008990000
echo "${T_Mab} [s] = $(bc -l <<< ${T_Mab}/31557600) [year]"
Here-strings are added since bash
3.0, if you are using older version, just use $(echo ${T_Mab}/31557600|bc -l)
.
With all these said, you really should consider bc
alternatives as suggested in the second answer of the linked question if you don't need arbitrary precision.
The syntax error is because bc
doesn't read "e" notation, and can be reproduced with a greatly simplified example:
$ bc -l <<<"6.00899e+09"
(standard_in) 1: syntax error
We'll need to change to a syntax it does understand; we can do that in Bash:
v=6.00899e+09
v=${v/e/*10^} # 6.00899*10^+09
v=${v/^+/^} # 6.00899*10^09
bc -l <<<"($v)"
6008990000.00000
Or simply launder through a tool that does understand the notation:
printf '%f\n' "$v" | bc -l