将红宝石浮点数向上或向下舍入到最接近的 0.05

问题描述 投票:0回答:9

我收到类似

的数字
2.36363636363636
4.567563
1.234566465448465
10.5857447736

如何让 Ruby 将这些数字向上(或向下)舍入到最接近的 0.05?

ruby floating-point rounding
9个回答
26
投票
[2.36363636363636, 4.567563, 1.23456646544846, 10.5857447736].map do |x|
  (x*20).round / 20.0
end
#=> [2.35, 4.55, 1.25, 10.6]

21
投票

查看此链接,我认为这就是您所需要的。 红宝石四舍五入

class Float
  def round_to(x)
    (self * 10**x).round.to_f / 10**x
  end

  def ceil_to(x)
    (self * 10**x).ceil.to_f / 10**x
  end

  def floor_to(x)
    (self * 10**x).floor.to_f / 10**x
  end
end

20
投票

一般来说,“四舍五入到最接近的x”的算法是:

round(x / precision)) * precision

有时最好乘以

1 / precision
,因为它是一个整数(因此它的工作速度更快一些):

round(x * (1 / precision)) / (1 / precision)

在你的情况下是:

round(x * (1 / 0.05)) / (1 / 0.05)

其计算结果为:

round(x * 20) / 20;

虽然我不懂Python,所以语法可能不正确,但我相信你能弄清楚。


11
投票

要四舍五入到最接近的 2 位:

(5.65235534).round(2)
#=> 5.65

8
投票

这是一个按任何给定步长值舍入的通用函数:

放置在库中:

lib/rounding.rb
class Numeric
  # round a given number to the nearest step
  def round_by(increment)
    (self / increment).round * increment
  end
end

和规格:

require 'rounding'
describe 'nearest increment by 0.5' do
  {0=>0.0,0.5=>0.5,0.60=>0.5,0.75=>1.0, 1.0=>1.0, 1.25=>1.5, 1.5=>1.5}.each_pair do |val, rounded_val|
    it "#{val}.round_by(0.5) ==#{rounded_val}" do val.round_by(0.5).should == rounded_val end
  end
end

及用法:

require 'rounding'
2.36363636363636.round_by(0.05)

hth.


5
投票

Ruby 2 现在有一个 round 函数:

# Ruby 2.3
(2.5).round
 3

# Ruby 2.4
(2.5).round
 2

ruby

2.4
中还有一些选项,例如:
:even
:up
:down
例如;

(4.5).round(half: :up)
 5

4
投票

可以使用

String
类的
%
方法对数字进行四舍五入。

例如

"%.2f" % 5.555555555

将给出

"5.56"
作为结果(字符串)。


3
投票

要获得不带小数的舍入结果,请使用 Float 的 .round

5.44.round
=> 5

5.54.round
=> 6

0
投票

我知道这个问题很老了,但我喜欢与世界分享我的发明以帮助其他人:这是一种用步长舍入浮点数,将小数舍入到最接近的给定数的方法;它对于四舍五入产品价格很有用,例如:

def round_with_step(value, rounding)
  decimals = rounding.to_i
  rounded_value = value.round(decimals)

  step_number = (rounding - rounding.to_i) * 10
  if step_number != 0
    step = step_number * 10**(0-decimals)
    rounded_value = ((value / step).round * step)
  end

  return (decimals > 0 ? "%.2f" : "%g") % rounded_value
end

# For example, the value is 234.567
#
# | ROUNDING | RETURN | STEP
# | 1        | 234.60 | 0.1
# | -1       | 230    | 10
# | 1.5      | 234.50 | 5 * 0.1 = 0.5
# | -1.5     | 250    | 5 * 10  = 50
# | 1.3      | 234.60 | 3 * 0.1 = 0.3
# | -1.3     | 240    | 3 * 10  = 30
© www.soinside.com 2019 - 2024. All rights reserved.