Ruby: Convert dollar (String) to cents (Integer)

£可爱£侵袭症+ 提交于 2019-12-04 10:22:17

You can use String#to_r ("to rational") to avoid round-off error.

def dollars_to_cents(dollars)
  (100 * dollars.to_r).to_i
end

dollars_to_cents("12")
  #=> 1200 
dollars_to_cents("10.25")
  #=> 1025 
dollars_to_cents("-10.25")
  #=> -1025 
dollars_to_cents("-0")
  #=> 0
d, c = dollar_amount_string.split(".")
d.to_i * 100 + c.to_i # => 532

I started with the original accepted answer, but had to make some important fixes along the way:

def dollars_to_cents(string=nil)
  # remove all the signs and formatting
  nums = string.to_s.strip.delete("$ CAD ,")
  # add CENTS if they do not exit
  nums = nums + ".00" unless nums.include?(".")
  return (100 * nums.strip.to_r).to_i
end

So far works with these inputs:

  • CAD 1,215.92
  • CAD 1230.00
  • $11123.23
  • $123
  • 43234.87
  • 43,234.87
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!