Ruby 保留两位小数有没有其它好的办法?

easonlovewan · October 22, 2015 · Last by easonlovewan replied at October 22, 2015 · 2125 hits

有其它简介的写法吗?

(num*100).round.to_f/100

Prepends="
  def round(i=0)                                   
    (self.to_f * 10**i ).to_i.to_f / (10**i)
  end
"

class Object
  eval Prepends
end


使用:

a=1.11111 p a.round(2)

Float 的 round 方法不能指定位数么?

pry(main)> 1.2222.round 2
=> 1.22

"%.2f" % 1.2345

1.2345.round 2

#1 楼 @sevk 尴尬了。。。。

You need to Sign in before reply, if you don't have an account, please Sign up first.