Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
也许标题令人困惑,但我会尝试用例子来解释:
给定一个精度 = 2 的浮点数,我希望能够舍入到其最接近的整数或最接近的 0.5。例子:
Given: 4.12 --> 4 4.24 --> 4 4.25 --> 4.5 4.33 --> 4.5 4.53 --> 4.5 4.65 --> 4.5 4.75 --> 5 4.84 --> 5
在 Ruby 中执行此操作的好方法是什么?
乘以 2,四舍五入,除以 2。
[4.12, 4.24, 4.25, 4.33, 4.53, 4.65, 4.75, 4.84].map do |x| r = (x * 2).round / 2.0 r.to_i == r ? r.to_i : r end => [4, 4, 4.5, 4.5, 4.5, 4.5, 5, 5]