1
1

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 3 years have passed since last update.

【Ruby】割り算の計算結果で小数点以下を得る方法

Last updated at Posted at 2021-03-12

使用環境

Ruby: 2.6.5

本題

基本的に、割り算の計算結果は整数値のみ出力されます。

puts 120 / 100
=> 1

もし小数点以下も算出したい場合、簡単な方法としては以下の2パターンがあります。

計算の最後に".to_f"をつける

puts 120 / 100 .to_f
=> 1.2

数値の末尾に".0"をつける

puts 120.0 / 100.0
=> 1.2

何故必要か

 Rubyにおいて、数値は大きく"integer(整数)クラス"と"float(浮動小数点数)クラス"に分かれます。そのため、integerクラス同士の数値で計算を行うと、計算結果もintegerクラス…つまり整数値になるということです。
 そのため、小数点以下も算出する際は「floatクラスに変換する」「floatクラスの数値で計算する」必要があるということです。

参考記事

1
1
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?