Skip to content

Commit

Permalink
Merge pull request #1 from duncanmmacleod/parse-str-decimal
Browse files Browse the repository at this point in the history
Use decimal.Decimal to parse strings
  • Loading branch information
Duncan Macleod committed Jun 13, 2017
2 parents 1248dd6 + 2260ff7 commit ad03d2f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
18 changes: 10 additions & 8 deletions ligotimegps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from math import (modf, log)
from functools import wraps
from decimal import Decimal

try:
from functools import total_ordering
Expand Down Expand Up @@ -86,17 +87,18 @@ def __init__(self, seconds, nanoseconds=0):
nanoseconds += ns * 1e9
elif not isinstance(seconds, six.integer_types):
if isinstance(seconds, (six.binary_type, six.text_type)):
sign = -1 if seconds.lstrip().startswith("-") else +1
try:
if "." in seconds:
seconds, ns = seconds.split(".")
ns = round(sign * float("." + ns) * 1e9)
else:
ns = 0
seconds = int(seconds)
except:
seconds = str(Decimal(seconds))
except ArithmeticError:
raise TypeError("invalid literal for LIGOTimeGPS(): %s"
% seconds)
sign = -1 if seconds.startswith("-") else +1
if "." in seconds:
seconds, ns = seconds.split(".")
ns = sign * int(ns.ljust(9, '0'))
else:
ns = 0
seconds = int(seconds)
nanoseconds += ns
elif (hasattr(seconds, "gpsSeconds") and
hasattr(seconds, "gpsNanoSeconds")): # lal.LIGOTimeGPS
Expand Down
3 changes: 3 additions & 0 deletions ligotimegps/test_ligotimegps.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ def test_creation(self):
a = LIGOTimeGPS("1", "234")
self.assertEqual(a.gpsSeconds, 1)
self.assertEqual(a.gpsNanoSeconds, 234)
a = LIGOTimeGPS("1.2345678987654321e9")
self.assertEqual(a.gpsSeconds, 1234567898)
self.assertEqual(a.gpsNanoSeconds, 765432100)
# check errors
self.assertRaises(TypeError, LIGOTimeGPS, 'test')
self.assertRaises(TypeError, LIGOTimeGPS, None)
Expand Down

0 comments on commit ad03d2f

Please sign in to comment.