我可以实施半轮甚至双轮吗? [英] Can I implement round half to even?

查看:39
本文介绍了我可以实施半轮甚至双轮吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在浮动上做轮到一半,即,

I need to do round half to even on floats, i.e.,

  1. 如果该值介于两个整数之间(决胜局,y 的小数部分正好是 0.5),则舍入到最接近的偶数,
  2. 否则,标准舍入(在 Ruby 中舍入到最近的整数).

这些是一些结果,例如:

These are some results, for example:

0.5=>0
1.49=>1
1.5=>2
2.5=>2
2.51=>3
3.5=>4

推荐答案

我会重新打开 Float 类来创建一个 round_half_to_even 函数:

I would reopen the Float class to create a round_half_to_even function :

class Float
  def round_half_to_even(precision)
    if self % 1 == 0.5
      floor = self.to_i.to_f
      return floor % 2 == 0 ? floor : floor + 1
    else
      return self.round(precision)
    end
  end
end

这篇关于我可以实施半轮甚至双轮吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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