0

I'm trying to use mechanize to pull some prices and I'm to the point where I can handle anything priced under $1,000 but as soon as anything hits above $1,000, the result is that I lose any integers after the thousands integer. For instance, $1,234.99 becomes $1.00.

This is what I have in my controller:

product_price = page.search(store.price_selector).first.text.match(/\b\d[\d,.]*\b/)  

product = Product.create!(
  price: product_price
   ...
 )

Price is a decimal i.e.

  :price, :decimal, :precision => 8, :scale => 2

Displaying in my Product view as such:

  <h4><%= number_to_currency(product.price, :unit => "$", :separator => ".") %></h4>

Here is what I tried to use as a fix in the controller - converting to a string first:

  product_price_str = page.search(store.price_selector).first.text.match(/\b\d[\d,.]*\b/).to_s

  product_price_str = product_price_str.split(".")[0]
  product_price = product_price_str.scan(/\d/).join('')

This solved the problem, only to create another - Now any price with a number other than zero for the decimal is rounded down to zero no matter what. For instance, 1,800.99 is displaying as 1,800.00

I know it's an easy answer (at least I hope), but I'm so new to this whole specific combination and rails in general so any help you've got would be much appreciated.

dstep
  • 135
  • 3
  • 15
  • You should remove comma `delete(',')` while populating your database with retrieved data to fix `.to_f` issue. – taro Apr 27 '14 at 10:20

2 Answers2

0

I'm not sure I understand your issue completely, but why not tweak your regex on data import so you have the price and only the price in a format suitable for inserting into your database?

> s = "or instance, $1,234.99 beco"
=> "or instance, $1,234.99 beco"
> s.match(/\$\d[\d,.]+/).to_s.gsub(/[^\d.]/, '')
=> "1234.99"
Philip Hallstrom
  • 19,673
  • 2
  • 42
  • 46
  • Thanks Philip - still not getting what I'm hoping for. Unfortunately I'm not very good at explaining the issue because I'm really not sure why I'm getting this problem. I'm going to just tough it out and use trial and error until I get something that works then I will post it here. – dstep Apr 28 '14 at 17:24
0

Here is what I did in the controller to solve the issue, at least for now:

  product_price_str = page.search(store.price_selector).first.text.match(/\b\d[\d,.]*\b/).to_s

  product_price_str = product_price_str.split(".")[0]
  product_price = product_price_str.scan(/\d/).join('')

Changed to

  product_price_str_decimal = "00"
  product_price_str_decimal = product_price_str.split(".")[1] if product_price_str.split(".")[1]
  product_price_str = product_price_str.split(".")[0]
   product_price = product_price_str + "." + product_price_str_decimal
dstep
  • 135
  • 3
  • 15