I have an Excel column containing part numbers. Here is a sample
As you can see, it can be many different datatypes: Float
, Int
, and String
. I am using roo
gem to read the file. The problem is that roo
interprets integer cells as Float
, adding a trailing zero to them (16431 => 16431.0). I want to trim this trailing zero. I cannot use to_i
because it will trim all the trailing numbers of the cells that require a decimal in them (the first row in the above example) and will cut everything after a string char in the String
rows (the last row in the above example).
Currently, I have a a method that checks the last two characters of the cell and trims them if they are ".0"
def trim(row)
if row[0].to_s[-2..-1] == ".0"
row[0] = row[0].to_s[0..-3]
end
end
This works, but it feels terrible and hacky. What is the proper way of getting my Excel file contents into a Ruby data structure?
or, from string:
For those using Rails,
ActionView
has anumber_with_precision
method that takes astrip_insignificant_zeros: true
argument to handle this.http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision
This should cover your needs in most cases:
some_value.gsub(/(\.)0+$/, '')
It trims all trailing zeroes and a decimal point followed only by zeroes. Otherwise, it leaves the string alone.
It's also very performant, as it is entirely string-based, requiring no floating point or integer conversions. (Assuming your input value is already a string)
Numeric values are returned as type :float