Mike Mike - 1 month ago 13
Ruby Question

How do I write my time conversion function to account for places after the decimal point?

I’m using Rails 4.2.7. I have this function for converting a string (meant to represent a time duration) into milliseconds …

def duration_in_milliseconds(input)
if input
input.split(':').map(&:to_i).inject(0) { |a, b| a * 60 + b } * 1000
else
0
end
end


Problem is, the above doesn’t take account over if there are tenths of a second (a decimal place). So passing this argument “19:14.1” gets the same result as passing this argument “19:14”. How can I make adjustments to the above so that it will account for the part of the duration after the decimal place?

Answer

Just convert it to Float while processing instead of Integer:

  def duration_in_milliseconds(input)
    if input
      input.split(':').map(&:to_f).inject(0) { |a, b| a * 60 + b } * 1000
    else
      0
    end
  end

duration_in_milliseconds('19:14')
#=> 1154000.0
duration_in_milliseconds('19:14.1')
#=> 1154100.0
Comments