Round a number up in ruby

回眸只為那壹抹淺笑 提交于 2019-12-25 01:45:51

问题


Just wondering how would i round the number "15.755" up to "15.76" in ruby.

I have tried the round method, but doesnt produce the result im looking for.

Thanks


回答1:


Is this not what you want?

>> 15.755.round(2)
=> 15.76

Ah, you are probably using 1.8 (why btw?). There you can do the following:

>> (15.755 * 100).round / 100.0
=> 15.76

You could wrap that up in a helper function:

def round(n, precision)
  raise "Precision needs to be >= 0" if precision < 0
  power_of_ten = 10 ** precision
  (n * power_of_ten).round / power_of_ten.to_f
end

round(15.755, 2) #=> 15.76


来源:https://stackoverflow.com/questions/7837815/round-a-number-up-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!