Ruby:将美元(String)转换为美分(整数)

abt*_*ree 4 ruby currency

如何将带有美元金额的字符串转换为"5.32""100"等于整数金额,如532或等10000

我有一个解决方案如下:

dollar_amount_string = "5.32"
dollar_amount_bigdecimal = BigDecimal.new(dollar_amount_string)
cents_amount_bigdecimal = dollar_amount_bigdecimal * BigDecimal.new(100)
cents_amount_int = cents_amount_bigdecimal.to_i
Run Code Online (Sandbox Code Playgroud)

但它似乎很不稳定.我想确定,因为这将是PayPal API的输入.

我也尝试了金钱宝石,但它无法将字符串作为输入.

Car*_*and 18

您可以使用String#to_r("to rational")来避免舍入错误.

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
Run Code Online (Sandbox Code Playgroud)