简体   繁体   English

如何将浮点数存储为文本而不会丢失精度?

[英]How to store a floating point number as text without losing precision?

Like the question says. 就像问题所说的那样。 Converting to / from the (truncated) string representations can affect their precision. 转换为(截断的)字符串表示可能会影响它们的精度。 But storing them in other formats like pickle makes them unreadable (yes, I want this too). 但是将它们存储在其他格式(如泡菜)中会使它们变得不可读(是的,我也想要这样)。

How can I store floating point numbers in text without losing precision? 如何在文本中存储浮点数而不会丢失精度?

Store it in binary or a power thereof. 将其存储在二进制或其中。

>>> (3.4).hex()
'0x1.b333333333333p+1'

>>> float.fromhex('0x1.b333333333333p+1')
3.4

I'd suggest using the builtin function repr() . 我建议使用内置函数repr() From the documentation: 从文档:

repr(object) -> string repr(object) - > string

Return the canonical string representation of the object. 返回对象的规范字符串表示形式。 For most object types, eval(repr(object)) == object. 对于大多数对象类型,eval(repr(object))== object。

pickle.dumps会这样做,但我相信float(str(floatval)) == floatval也是如此 - 至少在同一系统上......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM