29
23

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で小数点桁数指定

Last updated at Posted at 2015-11-22

Rubyで少数以下の桁数を指定して表示したかったのでメモ

  • sprintf(or format)を使う場合(文字列を返す)
test = 1.2345
puts sprintf("%.2f", test) # format("%.2f", test)も同様
  • round関数を使う場合
    この場合数値(Integer or Float)を返すので注意してください
    また、四捨五入してしまうので注意!
1.2345.round    #=> 1
1.2345.round(2) #=> 1.23
1.2345.round(3) #=> 1.235 (四捨五入)
puts 1.2345.round(3) #=> 1.235
29
23
4

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
29
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?