在 Bash 中進行除法是否可以得到十進位輸出?

在 Bash 中進行除法是否可以得到十進位輸出?

基本上在 Bash 中,我想做的是從用戶輸入秒數並找到小時數。所以基本上如果使用者輸入 35 輸出應該是 0.00972222。

但 bash 給我的是零。

這是我的命令:

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

有沒有辦法讓它在我輸入 35 時列印出 0.00972222 。

謝謝!

答案1

在這裡試試這個

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

所以你的命令看起來像

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

若要控制列印的有效位數,請使用scale=N。例如:

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

如果你還想列印開頭0(奇怪的是,bc不會輕易做到),您可以將數字輸入printf(也可以為您向上/向下捨去):

$ printf '%.3f\n' $(echo "35/3600" | bc -l)
0.010
$ printf '%.4f\n' $(echo "35/3600" | bc -l)
0.0097

相關內容