ruby - In rails removing $ and , from a price field -
i saving price string database in decimal type column. price comes in "$ 123.99" fine because wrote bit of code remove "$ " (the dollar sign , space). seem have forgotten price may include comma. "$ 1,234.99" breaks code. how can remove comma?
this code remove dollar sign , space:
def price=(price_str) write_attribute(:price, price_str.sub("$ ", "")) # possible code remove comma also? end
you can there 2 ways easily.
string's delete
method removing occurrences of target strings:
'$ 1.23'.delete('$ ,') # => "1.23" '$ 123,456.00'.delete('$ ,') # => "123456.00"
or, use string's tr
method:
'$ 1.23'.tr('$, ', '') # => "1.23" '$ 123,456.00'.tr('$ ,', '') # => "123456.00"
tr
takes string of characters search for, , string of characters used replace them. consider chain of gsub
methods, 1 each character.
but wait! there's more! if replacement string empty, characters in search string removed.
Comments
Post a Comment