From ad203bcb2be17e06909ab6d67ab2475673673bbc Mon Sep 17 00:00:00 2001 From: Andreas Eger Date: Sun, 11 Dec 2016 03:30:08 +0100 Subject: [PATCH 1/2] fix floating point accuracy problem in Timestamp#to_f `.quo` return the most exact devision which fixes accuracy problems for the timestamp coercion --- ruby/lib/google/protobuf/well_known_types.rb | 2 +- ruby/tests/well_known_types_test.rb | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/ruby/lib/google/protobuf/well_known_types.rb b/ruby/lib/google/protobuf/well_known_types.rb index 547de87493..921ddbc06f 100644 --- a/ruby/lib/google/protobuf/well_known_types.rb +++ b/ruby/lib/google/protobuf/well_known_types.rb @@ -80,7 +80,7 @@ module Google end def to_f - self.seconds + (self.nanos.to_f / 1_000_000_000) + self.seconds + (self.nanos.quo(1_000_000_000)) end end diff --git a/ruby/tests/well_known_types_test.rb b/ruby/tests/well_known_types_test.rb index 9b46632b72..ad8531d9b7 100644 --- a/ruby/tests/well_known_types_test.rb +++ b/ruby/tests/well_known_types_test.rb @@ -13,10 +13,15 @@ class TestWellKnownTypes < Test::Unit::TestCase assert_equal Time.at(12345), ts.to_time assert_equal 12345, ts.to_i - ts.from_time(Time.at(123456, 654321)) + time = Time.at(123456, 654321) + ts.from_time(time) assert_equal 123456, ts.seconds assert_equal 654321000, ts.nanos - assert_equal Time.at(123456.654321), ts.to_time + assert_equal time, ts.to_time + + time = Time.now + ts.from_time(time) + assert_equal time.to_f, ts.to_time.to_f end def test_duration From 78cb804063716767966cdcd86c66500df342ad33 Mon Sep 17 00:00:00 2001 From: Andreas Eger Date: Sat, 13 May 2017 22:20:45 +0200 Subject: [PATCH 2/2] change test for nanosecond accurate timestamps --- ruby/tests/well_known_types_test.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ruby/tests/well_known_types_test.rb b/ruby/tests/well_known_types_test.rb index ad8531d9b7..bd24c32884 100644 --- a/ruby/tests/well_known_types_test.rb +++ b/ruby/tests/well_known_types_test.rb @@ -13,15 +13,18 @@ class TestWellKnownTypes < Test::Unit::TestCase assert_equal Time.at(12345), ts.to_time assert_equal 12345, ts.to_i + # millisecond accuracy time = Time.at(123456, 654321) ts.from_time(time) assert_equal 123456, ts.seconds assert_equal 654321000, ts.nanos assert_equal time, ts.to_time - time = Time.now + # nanosecond accuracy + time = Time.at(123456, Rational(654321321, 1000)) ts.from_time(time) - assert_equal time.to_f, ts.to_time.to_f + assert_equal 654321321, ts.nanos + assert_equal time, ts.to_time end def test_duration