【问题标题】:How do I write my time conversion function to account for places after the decimal point?如何编写时间转换函数来计算小数点后的位数?
【发布时间】:2017-02-14 05:08:04
【问题描述】:

我使用的是 Rails 4.2.7。我有这个函数用于将字符串(表示持续时间)转换为毫秒......

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

问题是,如果有十分之一秒(小数位),上述内容并没有考虑在内。因此,传递这个参数“19:14.1”与传递这个参数“19:14”得到相同的结果。如何对上述内容进行调整,使其占小数点后的持续时间部分?

【问题讨论】:

    标签: ruby-on-rails ruby time format duration


    【解决方案1】:

    在处理时将其转换为 Float 而不是 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多