我正在学习Ruby,目前我正在学习数字.因此,据我所知,有五种方法(也许更多)可以将整数和浮点数相互强制:

  • Integer#to_f:强制使用新的浮动
  • Float#ceil:向上舍入到最接近的整数
  • Float#floor:向下舍入到最接近的整数
  • Float#round:四舍五入到最接近的整数
  • Float#to_i:截断到最接近的整数

"四舍五入"和"截断"到最接近的整数有什么区别?

当我测试它的时候.

puts 34.4.to_i()
puts 34.4.floor()

...其结果是相同的值:

34
34

推荐答案

不同之处在于,to_i基本上只删除浮点数中的小数.而float向下舍入到下一个较低的整数.在处理负值浮动时,这种差异更容易看出:

-34.4.floor
#=> -35

-34.4.to_i
#=> -34

可能值得注意的是,Float#round支持不同的舍入模式.

`:up` or `nil`: round away from zero:

2.5.round(half: :up)      # => 3
3.5.round(half: :up)      # => 4
(-2.5).round(half: :up)   # => -3

`:down`: round toward zero:

2.5.round(half: :down)    # => 2
3.5.round(half: :down)    # => 3
(-2.5).round(half: :down) # => -2

`:even`: round toward the candidate whose last nonzero digit is even:

2.5.round(half: :even)    # => 2
3.5.round(half: :even)    # => 4
(-2.5).round(half: :even) # => -2

Ruby相关问答推荐

Ruby Case语句和固定,不适用于attr_reader

环绕分隔线,保留第一列,最小最终长度

Jekyll 默认安装没有 _layouts 目录

`Range#include?` 和 `Range#cover?` 有什么区别?

构造Ruby的现代方法是什么?

Ruby检测方法

有没有办法通过哈希初始化对象?

如何拯救 Ruby 中的 eval?

如何正确截断表格?

如何通过反射获取 Ruby 的 Module 类定义的常量?

按键对哈希进行分组并对值求和

来自 Linux 上的命令队列的并行处理(bash、python、ruby ......随便)

从Electron邮件中删除签名和回复

将字符串与多个模式匹配

从 Ruby 中的 DateTime 中减go n 小时

Ruby 被空格分割

include_examples和it_behaves_like有什么区别?

何时在 Ruby 中使用 `require`、`load` 或 `autoload`?

相当于 Ruby 的 cURL?

将哈希传递给函数 ( *args ) 及其含义