将Ruby浮点向上或向下舍入到最接近的0.05

3xiyfsfu  于 2023-08-04  发布在  Ruby
关注(0)|答案(9)|浏览(115)

我得到的数字是

2.36363636363636
4.567563
1.234566465448465
10.5857447736

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

zf2sa74q

zf2sa74q1#

[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]

字符串

ao218c7q

ao218c7q2#

看看这个链接,我想这就是你需要的。Ruby rounding

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

字符串

n1bvdmb6

n1bvdmb63#

通常,用于“舍入到最接近的 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,虽然,所以语法可能不正确,但我相信你可以弄清楚。

xsuvu9jc

xsuvu9jc4#

要四舍五入到最接近的2位,请改为:

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

字符串

vwkv1x7d

vwkv1x7d5#

下面是一个通用函数,它可以舍入任何给定的步长值:
在lib中放置:

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

字符串
和spec:

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.

72qzrwbm

72qzrwbm6#

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

guicsvcw

guicsvcw7#

可以使用String类的%方法对数字进行舍入。
比如说

"%.2f" % 5.555555555

字符串
将给予"5.56"作为结果(一个字符串)。

4sup72z8

4sup72z88#

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

5.44.round
=> 5

5.54.round
=> 6

字符串

pvabu6sv

pvabu6sv9#

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

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

字符串

相关问题