在float中显示两个十进制数字,带一个十进制数字

时间:2016-11-04 17:51:42

标签: ruby

我通过整数类型存储为cents的数据库中的钱。显示时:我将其转换为浮点数,因为我想以美元金额显示金额。我总是希望用两位数字来显示数字:

例如:

5000 => 50.00
500  => 5.00
50   => 0.50
5    => 0.05
0    => 0.00

最难的是让50转换为0.50,因为它是一个浮点数,它想要转换为0.5

当前不起作用的方法:

def cents_to_currency_string
  return if cents.nil?
  (cents.to_f / 100)
end

3 个答案:

答案 0 :(得分:4)

利用您自己的实施:

def cents_to_currency_string(cents)
  return if cents.nil?
  dollars = cents.to_f/100
  '%.2f' % dollars
end

答案 1 :(得分:1)

您可以稍微编辑一下您的方法:

def cents_to_currency_string(cents)    
    return if cents.nil? 
    (cents.to_f / 100).to_s.ljust(4,'0')
end

答案 2 :(得分:0)

你可以通过几种不同的方式做到这一点。最简单的方法是做这样的事情

def display(n)
  if n % 100 < 10
    "$#{n/100}.0#{n%100}"
  else 
    "$#{n/100}.#{n%100}"
  end
end

然后你可以像这样显示它

puts centize(n)
相关问题