浮点数字格式不用红宝石舍入(Float number format without rounding in ruby)
有一个浮点数num = 22.0098 。 我如何格式化它以限制浮点数后的3位数? 我试过sprintf('%.3f',num)但是返回值是22.010 ,但我需要22.009
There is a float number num = 22.0098. How can I format it to limit 3 digits after floating point? I tried sprintf('%.3f',num) but return is 22.010, I need 22.009 though
最满意答案
不幸的是,不像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"Unfortunately, unlike Float#round, Float#floor does not accept an amount of digits. The below code implements the desired behaviour.
def floor_float input, digits = 3 input.divmod(10 ** -digits).first / (10 ** digits).to_f endThis might be used as monkey patch:
class Float def floor_ext digits = 3 self.divmod(10 ** -digits).first / (10 ** digits).to_f end end 22.0098.floor_ext #⇒ 22.009Probably more succinct variant as suggested by @Stefan:
class Float def floor_ext digits = 3 div(10 ** -digits).fdiv(10 ** digits) end end 22.0098.floor_ext #⇒ 22.009Or, one might deal with strings explicitly:
i, f = 22.0098.to_s.split('.') #⇒ [ "22", "0098" ] [i, f[0..2]].join('.') #⇒ "22.009"更多推荐
发布评论