22
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

shellscriptで小数演算

Posted at

shellscriptで小数演算をしたかったのでメモ。

小数演算

###echobcを利用
exprコマンドなどは小数演算できないので、
echoコマンドで数式を作成し、それをbcコマンドに渡して計算する。

RESULT=`echo "scale=5; 10.0 / 3.0" | bc`
echo $RESULT
#=> 3.33333

小数点以下の桁数をscaleにて指定する。

指定桁数出力

演算の精度を保つため、上記のように計算は小数点以下5桁で行うけれど、表示は小数点以下2桁とかにしたい場合
(というか、桁数を指定したい場合)

RESULT=`echo "scale=5; 10.0 / 3.0" | bc`
printf "%.2f" $RESULT
#=> 3.33

printfで桁数を指定。

22
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?