【问题标题】:Convert unicode to python float but keep the decimal places将 unicode 转换为 python float 但保留小数位
【发布时间】:2016-05-24 20:23:55
【问题描述】:

我有一个 unicode 字符串 x = u'12345678.87654321',我想在 python 中将其转换为 float

float(x)

它被转换为12345678.88。似乎float() 自动将数字四舍五入到小数点后两位。我想保留 unicode 字符串中的任何内容(小于 10 位小数)。有什么好的选择?

编辑:我很抱歉。我使用的示例未经过测试。我将只使用我的真实数据: 我有一个 unicode 字符串 u'1464106296.285190'。这是无法转换为浮点数并保留所有小数位的。

【问题讨论】:

  • 您使用的是 Python 3 吗?我在 2.7 中没有得到这个结果。
  • 这里有两个问题:1)float没有无限精度,16位端对端大约是最大值; 2) Python 不一定会输出所有数字,除非你使用格式化来强制它。
  • 请查看我的编辑。我同意@MarkRansom 的观点,即浮点数端到端有 16 位数字。如果我想超越这个限制怎么办?
  • 这是干什么用的?您真的需要比float 提供的精度更高吗?
  • @RadLexus 如果您在 Python 2 中使用 print,它很容易重现。而且我在问题中没有看到任何关于库推荐的请求。

标签: python unicode


【解决方案1】:

使用decimal.Decimal

In [103]: import decimal

In [104]: D = decimal.Decimal

In [109]: D(u'1464106296.285190')
Out[109]: Decimal('1464106296.285190')

In [110]: float(u'1464106296.285190')
Out[110]: 1464106296.28519

In [111]: print(D(u'1464106296.285190'))
1464106296.285190

【讨论】:

    【解决方案2】:

    它转换得很好。 Python 浮点数可以保持大约 16 位的精度。 print 在 Python 2.7 中进行了一些默认舍入以显示它,但无论哪种方式,值的转换都是相同的。您可以格式化该值以提高打印精度。以下是 Python 3 和 2 中的示例。请注意,转换精确到 16 位。

    Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> s=u'1464106296.285190'
    >>> f=float(s)
    >>> f
    1464106296.28519
    >>> format(f,'.30f')
    '1464106296.285190105438232421875000000000'
    >>> print(f)
    1464106296.28519
    
    Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> s=u'1464106296.285190'
    >>> f=float(s)
    >>> f
    1464106296.28519
    >>> format(f,'.30f')
    '1464106296.285190105438232421875000000000'
    >>> print(f)
    1464106296.29
    

    【讨论】:

      猜你喜欢
      • 2011-03-30
      • 2017-02-03
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      相关资源
      最近更新 更多