Search code examples
rubytimebigdecimal

How to convert time to bigdecimal with ruby?


For example, I have a time data with string format:

00:25:23;16

I want to convert it to BigDecimal and tried:

a = '00:25:23;16'.to_d
=> #<BigDecimal:96cb548,'0.0',9(18)>

When I check a:

a.floor
=> 0

It looks not the true value. Then how to convert it the right way?

Addition

I expect the bigdecimal value like this(Maybe not a right value):

1543.123

Solution

  • Assuming the ;16 means milliseconds then maybe you are looking for this?

    > str = "00:25:23;16"
    => "00:25:23;16"
    > h, m, s, ms = str.split(/[:;]/).map(&:to_f)
    => [0.0, 25.0, 23.0, 16.0]
    > h * 3600 + m * 60 + s + ms/1000
    => 1523.016