Skip to content

Commit a622e5e

Browse files
committed
Add float_factory option to .sym to control str->float conversion on load
For example, I want to use decimal.Decimal() to avoid loss of accuracy when transitioning str->float->decimal.Decimal. ``` >>> import decimal >>> decimal.Decimal(float('0.1')) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> decimal.Decimal('0.1') Decimal('0.1') ```
1 parent 7e21a2c commit a622e5e

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

canmatrix/canmatrix.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -188,15 +188,17 @@ def multiplex(value):
188188
multiplex = value
189189
return multiplex
190190

191+
float_factory = kwargs.pop('float_factory', float)
192+
191193
args = [
192194
('startBit', 'startbit', int, 0),
193195
('signalSize', 'signalsize', int, 0),
194196
('is_little_endian', 'is_little_endian', bool, True),
195197
('is_signed', 'is_signed', bool, True),
196-
('factor', 'factor', float, 1),
197-
('offset', 'offset', float, 0),
198-
('min', 'min', float, None),
199-
('max', 'max', float, None),
198+
('factor', 'factor', float_factory, 1),
199+
('offset', 'offset', float_factory, 0),
200+
('min', 'min', float_factory, None),
201+
('max', 'max', float_factory, None),
200202
('unit', 'unit', None, ""),
201203
('receiver', 'receiver', None, []),
202204
('comment', 'comment', None, None),

canmatrix/sym.py

+5
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ def load(f, **options):
261261

262262
calc_min_for_none = options.get('calc_min_for_none')
263263
calc_max_for_none = options.get('calc_max_for_none')
264+
float_factory = options.get('float_factory')
264265

265266
class Mode(object):
266267
glob, enums, send, sendReceive, receive = list(range(5))
@@ -449,6 +450,8 @@ class Mode(object):
449450
extras['calc_min_for_none'] = calc_min_for_none
450451
if calc_max_for_none is not None:
451452
extras['calc_max_for_none'] = calc_max_for_none
453+
if float_factory is not None:
454+
extras['float_factory'] = float_factory
452455

453456
signal = Signal(frameName + "_MUX",
454457
startBit=startBit,
@@ -478,6 +481,8 @@ class Mode(object):
478481
extras['calc_min_for_none'] = calc_min_for_none
479482
if calc_max_for_none is not None:
480483
extras['calc_max_for_none'] = calc_max_for_none
484+
if float_factory is not None:
485+
extras['float_factory'] = float_factory
481486

482487
signal = Signal(sigName,
483488
startBit=startBit,

0 commit comments

Comments
 (0)