views:

168

answers:

3

After spliting a tab delimited file I have my required values in a string variable. Unfortunately the source of this file is out of my control.

Here are three exact example of what the value might hold:

  1. " 5.344"
  2. " -2.345"
  3. " -.977"

Notice the white space, no '0' prefixing the decimal points and the double quotes are in the string. Once I have each one in my field variable this is what I am currently doing:

int_val = BigDecimal(value_as_string.gsub(/-\./,"-0.").gsub(/\"/,'').strip).round(0).to_i

I need each one rounded to the nearest integer (.to_i rounds down). Any better ideas would be much appreciated as I can help but this this stinks!?

+7  A: 
def round(s)
    s.to_f.round
end

round("5.344") # 5
round("-2.345") # -2
round("-.977") # -1
Chris Doggett
Thanks for that answer. Although it will still need a little extra as my variable is like:round('"5.344"')I.e. the string contains the double quotes.
tsdbrown
s.gsub!('"','').to_f.round
krusty.ar
@tsdbrown: 's' in this case would be the string after you'd already done your gsub as mentioned in your initial code. You'd be calling round(value_as_string.gsub(/-\./,"-0.").gsub(/\"/,'').strip).
Chris Doggett
A: 
def round(str)
  val = BigDecimal(str.gsub(/-\./,"-0.").gsub(/\"/,'').strip)

  if val < 0 then
    return val.floor.to_i
  else
    return val.ceil.to_i
  end
end
Ahsan Ali
A: 

This expression will clean the string, removing everyting but digits, - or decimal dot in the first gsub and the second gsub will add a 0 before the . (keeping the - sign if it exists)

some_value.gsub(/[^-\.0-9]/, '').gsub(/^(-?)(\.)/,'\10\2')

Then you will need to round it, with to_f.round should be enough. So the final thing would look like

def myround(value)
  value.gsub(/[^-\.0-9]/, '').gsub(/^(-?)(\.)/,'\10\2').to_f.round
end