【发布时间】:2014-09-16 16:00:09
【问题描述】:
我想在 python 中使用 Decimal() 数据类型并将其转换为整数和指数,以便我可以将该数据发送到具有全精度和小数控制的微控制器/PLC。 https://docs.python.org/2/library/decimal.html
我已经让它工作了,但它很老套;有人知道更好的方法吗?如果不是,我会采取什么途径自己编写一个较低级别的“as_int()”函数?
示例代码:
from decimal import *
d=Decimal('3.14159')
t=d.as_tuple()
if t[0] == 0:
sign=1
else:
sign=-1
digits= t[1]
theExponent=t[2]
theInteger=sign * int(''.join(map(str,digits)))
theExponent
theInteger
对于那些没有编程 PLC 的人,我的替代方法是使用 int 并在两个系统中声明小数点或使用浮点(只有某些 PLC 支持)并且是有损的。所以你可以看到为什么能够做到这一点会很棒!
提前致谢!
【问题讨论】:
-
太棒了!多谢你们!我采取了rvraghav93的绩效代码,并添加了这里回复的每个人是代码(paste.ubuntu.com/7856669),这里是崩溃:rvraghav93:1.11100006104 ericnutsch:4.22099995613 Smisseim:4.70300006866 Mark_ransom:7.80999994278 ehsan_abd:10.651999504 span
标签: python decimal microcontroller data-conversion plc