浮点数格式没有在ruby中舍入
发布时间:2020-12-17 03:50:01 所属栏目:百科 来源:网络整理
导读:有一个浮点数num = 22.0098.如何将其格式化为浮点后限制3位数?我试过sprintf(‘%.3f’,num),但返回是22.010,但我需要22.009 解决方法 不幸的是,与 Float#round 不同,Float#floor不接受一定数量的数字.以下代码实现了所需的行为. def floor_float input,dig
有一个浮点数num = 22.0098.如何将其格式化为浮点后限制3位数?我试过sprintf(‘%.3f’,num),但返回是22.010,但我需要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" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |