7

Basically in Bash, what I'm trying to do is take a input of seconds from a user and find the hours. So basically if the user enter 35 the output should be 0.00972222.

But bash gives me is a zero.

heres the command I have:

echo "Enter the seconds you wish to convert to hours: " && read sec && echo " $((sec/3600)) is the amount of hours "

Is there a way I can make it so it prints out 0.00972222 if I enter 35.

Thanks!

3
  • 2
    Bash operated with whole numbers, so you'll have to use additional tools e.g. bc or awk: awk -v sec=$sec 'BEGIN{print sec / 3600 " is the amount of hours"}' – Costas Feb 19 '16 at 7:30
  • Is there a way shorter way, if I use bc? I tried doing bc -l but all I get is "(standard_in) 1: parse error – shawn edward Feb 19 '16 at 7:36
  • Bash does not support rational or floating point numbers, only integers – fpmurphy Feb 19 '16 at 11:04
14

Here try this

echo $(echo "35/3600" | bc -l )

so your command would look like

echo "Enter the seconds you wish to convert to hours: " && read sec && echo " $(echo "$sec/3600" | bc -l ) is the amount of hours "

To control the number of significant digits printed, use scale=N. For example:

$ echo "scale=3; 35/3600" | bc -l 
.009

If you also want to have the leading 0 printed (which, weirdly enough, bc won't do easily), you can feed the number to printf (which can also round it up/down it for you):

$ printf '%.3f\n' $(echo "35/3600" | bc -l)
0.010
$ printf '%.4f\n' $(echo "35/3600" | bc -l)
0.0097
2
  • only con about using this is the amount of numbers after the decimals place but it works perfectly – shawn edward Feb 19 '16 at 7:51
  • @shawnedward you can control the decimal points. See edited answer. – terdon Feb 19 '16 at 10:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.