to_d总是在ruby中返回2个小数位 [英] to_d to always return 2 decimals places in ruby

查看:76
本文介绍了to_d总是在ruby中返回2个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理货币,我想将数字四舍五入到小数点后两位.即使数字是500.0,我也希望它是500.00以保持一致.当我执行"500.00" .to_d时,它将转换为500.0.

I'm dealing with currencies and I want to round down the number to 2 decimal places. Even if the number is 500.0, I would like it to be 500.00 to be consistent. When I do "500.00".to_d it converts it to 500.0.

什么是改变这种行为的好方法?我还使用此方法将其舍入到2位数字,并确保它始终具有2位小数.

Whats a good way of changing this behavior? I also use this method to round down to 2 digits and make sure it always has 2 decimals.

def self.round_down(x, n=2)
    s = x.to_s      
    l = s.index('.') ? s.index('.') + 1 + n : s.length
    s = s[0, l]
    s =  s.index('.') ? s.length - (s.index('.') + 1) == 1 ? s << '0' : s : s << '.00'      
    s.to_f
end

推荐答案

除了mcfinnigan的答案外,您还可以使用以下代码获得2位小数位

In addition to mcfinnigan's answer, you can also use the following to get 2 decimal places

'%.2f' % 500 # "500.00"

该用例称为字符串格式运算符

这篇关于to_d总是在ruby中返回2个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆