有一个浮点数num = 22.0098
,我该如何格式化它以限制小数点后3位?我尝试过sprintf('%.3f',num)
但返回值是22.010
,我需要的是22.009
有一个浮点数num = 22.0098
,我该如何格式化它以限制小数点后3位?我尝试过sprintf('%.3f',num)
但返回值是22.010
,我需要的是22.009
我认为可以使用BigDecimal,但不确定是否过于复杂:
require 'bigdecimal'
BigDecimal::new("22.0098").truncate(3).to_f
#=> 22.009
很不幸,与Float#round
不同的是,Float#floor
不接受数字数量。下面的代码实现了所需的行为。
def floor_float input, digits = 3
input.divmod(10 ** -digits).first / (10 ** digits).to_f
end
这可能被用作猴子补丁:
class Float
def floor_ext digits = 3
self.divmod(10 ** -digits).first / (10 ** digits).to_f
end
end
22.0098.floor_ext
#⇒ 22.009
根据@Stefan的建议,以下是更加简洁的变体:
class Float
def floor_ext digits = 3
div(10 ** -digits).fdiv(10 ** digits)
end
end
22.0098.floor_ext
#⇒ 22.009
i, f = 22.0098.to_s.split('.')
#⇒ [ "22", "0098" ]
[i, f[0..2]].join('.')
#⇒ "22.009"
input.div(10 ** -digits).fdiv(10 ** digits)
。此外,在 Float
中,你可以省略 self
。 - Stefansprintf("%.6s", num)
# => "22.009"
num
的大小调整6
。
sprintf('%.3f', num - 0.0005)
。 - Stefan