0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Bashの除算では小数点以下は出力されない

Last updated at Posted at 2025-12-21

はじめに

qnote Advent Calendar 2025の22日目の記事です。
業務でBashを使っていたときに、意外な仕様だと思ったことがあるので書き残します。

Bashの四則演算

echo $((5 + 2)) # 7
echo $((5 - 2)) # 3
echo $((5 * 2)) # 10
echo $((5 / 2)) # 2
echo $((5 % 2)) # 1

基本的な演算ですが、除算(割り算)だけは小数点以下が切り捨てされ、結果は整数のみになります。
初めて見たときはバグったかと思いました。

なんで整数になるの?

Bashの仕様です。
厳密にいうと「小数部分を表現できないので整数部分だけ残る」です。
また、Bashの算術は内部でC言語が動いているため、切り捨ての仕様になります。

The operators and their precedence, associativity, and values are the same as in the C language.(演算子とその優先順位、結合性、および値はC言語と同様である。)

でも小数点以下も扱いたいよね

外部コマンド(POSIXコマンド)を使用することで出力できます。
我々がよく使うlscatも外部コマンドの仲間です。

  • bc(basic calculator)コマンドで出力
echo "scale=1; 5 / 2" | bc # 2.5
  • awkコマンドで出力
awk 'BEGIN { print 5 / 2 }' # 2.5

さいごに

Bashなどのシェルスクリプトは記法が独特なので、読み書きが大変です。
全てのプログラマーが通る道だと思っているので、頑張って覚えていきたいですね!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?