49
30

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.

[ruby] 割り算で小数点以下も必要な場合

Posted at

割り算

float.rb
255/12

こんな計算をすると、小数点がどっか行っちゃう。

float.rb
[1] pry(main)> 255/12
=> 21

これは別にどっか行っちゃう訳ではなく、整数/整数=整数を返す仕様らしい。
勝手にfloatにはならない。

一覧表

|除算の対象|除算する数値|/|div|quo|
|------+-----+----+----+---|
|整数|整数|整数|整数|浮動|小数点数|
|整数|浮動小数点数|浮動小数点数|整数|浮動小数点数|
|浮動小数点数|整数|浮動小数点数|整数|浮動小数点数|
|浮動小数点数|浮動小数点数|浮動小数点数|整数|浮動小数点数|

float.rb
[2] pry(main)> 255/12.to_f
=> 21.25
[3] pry(main)> 255.quo(12)
=> (85/4)
[4] pry(main)> 255.quo(12).to_f
=> 21.25
[5] pry(main)> 255.to_f/12.to_f
=> 21.25

floatを明示すれば無問題

参考

除算による商と剰余を取得する - 数値(Numeric)クラス - Ruby入門

49
30
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
49
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?