我有
string = "$575.00 "
string.to_f
// => 0.0
string = "575.00 "
string.to_f
// => 575.0
传入的值采用这种格式,我需要将任何建议插入到十进制的数据库字段中
"$575.00 "
最佳答案
我们经常这样做,因此我们为 String
编写了一个名为 cost_to_f
的扩展:
class String
def cost_to_f
self.delete('$,').to_f
end
end
我们将此类扩展存储在 config/initializers/extensions/string.rb
中。
然后您可以简单地调用:
"$5,425.55".cost_to_f #=> 5425.55
如果您很少使用此方法,最好的办法是简单地创建一个函数,因为向核心类添加函数并不是我轻易推荐的事情:
def cost_to_f(string)
string.delete('$,').to_f
end
如果你在多个类中需要它,你总是可以把它放在一个模块中,然后在你需要的任何地方include
那个模块。
还有一点。您提到您需要在将此字符串写入数据库时对其进行处理。使用 ActiveRecord,最好的方法是:
class Item < ActiveRecord::Base
def price=(p)
p = p.cost_to_f if p.is_a?(String)
write_attribute(:price, p)
end
end
编辑:更新为使用String#delete
!
关于ruby-on-rails - 剥离字符串的第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3596105/