Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripping the first character of a string

i have

string = "$575.00 "
string.to_f
// => 0.0

string = "575.00 "
string.to_f
// => 575.0

the value coming in is in this format and i need to insert into a database field that is decimal any suggestions

"$575.00 " 
like image 588
Matt Elhotiby Avatar asked Feb 26 '23 08:02

Matt Elhotiby


1 Answers

We did this so often we wrote an extension to String called cost_to_f:

class String
  def cost_to_f
    self.delete('$,').to_f
  end
end

We store such extensions in config/initializers/extensions/string.rb.

You can then simply call:

"$5,425.55".cost_to_f   #=> 5425.55

If you are using this method rarely, the best bet is to simply create a function, since adding functions to core classes is not exactly something I would recommend lightly:

def cost_to_f(string)
  string.delete('$,').to_f
end

If you need it in more than one class, you can always put it in a module, then include that module wherever you need it.


One more tidbit. You mentioned that you need to process this string when it is being written to the database. With ActiveRecord, the best way to do this is:

class Item < ActiveRecord::Base
  def price=(p)
    p = p.cost_to_f if p.is_a?(String)  
    write_attribute(:price, p)
  end
end

EDIT: Updated to use String#delete!

like image 114
wuputah Avatar answered Mar 12 '23 05:03

wuputah