LoginSignup
4
6

More than 3 years have passed since last update.

小数第2位までRubyでtruncateする方法

Last updated at Posted at 2015-06-04

(追記) Ruby 2.4.0 からは期待通りの仕様になりました

RUBY_VERSION                    # => "2.4.0"
0.555.truncate(2)               # => 0.55

参考

サンプルコードでわかる!Ruby 2.4の新機能と変更点
http://qiita.com/jnchito/items/9f9d45581816f121af07

Ruby 2.4.0 未満では難しかった

round に引数を渡して四捨五入ができるなら、当然 truncate も同じように使えるんだろうと思いきや、なぜかできません。引数を受けつけないだと!?

0.555.round(2)                  # => 0.56
0.555.truncate(2) rescue $!     # => #<ArgumentError: wrong number of arguments (1 for 0)>

そこで、なんだかよくわからないけど BigDecimal に変換してみるとできました。

require "bigdecimal"
require "bigdecimal/util"
0.555.to_d.truncate(2).to_f     # => 0.55
4
6
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
4
6