GeekJock
GeekJock

Reputation: 11346

Ruby subtracting one microsecond when converting to string

I have a string timestamp:

ts = '1550989255.000300'

How can I parse ts in a Time or Datetime object as t, and have t.strftime('%6N') print correctly?

I did:

t = Time.at(ts.to_f)
t.strftime '%6N' #=> "000299"

Ruby chops off one microsecond when converting a timestamp to a string.

Upvotes: 1

Views: 137

Answers (3)

steenslag
steenslag

Reputation: 80085

Rationals are more exact than Floats, and they are used more and more in Ruby.

ts = '1550989255.000300'
t  = Time.at(ts.to_r)  # to_r: a rational
p t.strftime '%6N'     # => "000300"

Upvotes: 2

GeekJock
GeekJock

Reputation: 11346

This works:

ts = "1550989255.000300"
arr = ts.split('.')
t = Time.at(arr[0].to_i, arr[1].to_i)
t.strftime '%6N'

Upvotes: 1

Yossi
Yossi

Reputation: 12110

You are observing floating point math inaccuracy. If you need higher precision, you should use BigDecimal.

require 'bigdecimal'

ts = BigDecimal('1550989255.000300')
t  = Time.at(ts)
t.strftime '%6N'

=> "000300"

Upvotes: 4

Related Questions