我希望将任何给定数字四舍五入到Ruby中的八分之一或三分之一,以最接近的为准 .
我希望输出像 1/8
或 2/3
.
我尝试过以下方法:
scalar_in_eighths = (scalar * 8.0).round / 8.0
scalar_in_thirds = (scalar * 3.0).round / 3.0
thirds_difference = (scalar - scalar_in_thirds).abs
eighths_difference = (scalar - scalar_in_eighths).abs
compute_in_thirds = thirds_difference < eighths_difference
if compute_in_thirds
less_than_eighth = false
rounded_scalar = scalar_in_thirds
else
less_than_eighth = false
rounded_scalar = scalar_in_eighths
end
quotient, modulus = rounded_scalar.to_s.split '.'
quotient = quotient.to_f
modulus = ".#{modulus}".to_f
这适用于8个,但对于像 1.32
这样的数字,它会崩溃 .
对小数组件执行 modulus.numerator
和 modulus.denominator
将产生 6004799503160661
和 18014398509481984
之类的数字 .
有没有更好的方法来解决这个问题?
1 回答
这是你可以写的一种方式 .
Code
Examples