用 ruby​​ 将数字向上取整 [英] Round a number up in ruby

查看:275
本文介绍了用 ruby​​ 将数字向上取整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道如何将 ruby​​ 中的数字15.755"四舍五入为15.76".

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.

谢谢

推荐答案

这不是您想要的吗?

>> 15.755.round(2)
=> 15.76

啊,您可能使用的是 1.8(顺便说一句,为什么?).您可以在那里执行以下操作:

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

这篇关于用 ruby​​ 将数字向上取整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆