浮点数字格式不用红宝石舍入(Float number format without rounding in ruby)

编程入门 行业动态 更新时间:2024-10-26 11:30:04
浮点数字格式不用红宝石舍入(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 end

This 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.009

Probably 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.009

Or, one might deal with strings explicitly:

i, f = 22.0098.to_s.split('.') #⇒ [ "22", "0098" ] [i, f[0..2]].join('.') #⇒ "22.009"

更多推荐

本文发布于:2023-08-06 10:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1446716.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点   红宝石   格式   数字   Float

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!