你如何在ruby中强制实数的整数除法?
# integer division with integers - no problem
>> [ 7/2 , 7%2 ]
=> [3, 1]
# integer division with floats - '%' gives the remainder just fine...
# ...but for the quotient it used real division
>> [ 7.0/2 , 7.0%2 ]
=> [3.5, 1.0]
# This is what happens with non integer-y floats
>> [ 7.1/2 , 7.1%2 ]
=> [3.55, 1.0999999999999996]
我想要[ 3.0, 1.1 ]
。假设这不能在vanilla ruby中完成并需要使用gem?
答案 0 :(得分:7)
Numeric#divmod
来救援:
7.1.divmod 2
#⇒ [
# [0] 3,
# [1] 1.0999999999999996
# ]
或者,仅适用于商部分(归功于@Stefan):
7.1.div 2
#⇒ 3
答案 1 :(得分:1)
试试这个
require 'bigdecimal'
d = BigDecimal.new(7.1, 2)
=> #<BigDecimal:7fc2b199ab30,'0.71E1',18(27)>
d.divmod(2).map(&:to_f)
=> [3.0, 1.1]