python - 如何编写 float -> string 并获得与 "%.f"相同的数字

标签 python floating-point

今天我写了一个简单的函数,它通过反复修改 10 和除以 10 将 float 转换为字符串。

def to_string(x):
    r = ""
        while x >= 1.0:
            r = str(int(x%10)) + r
            x /= 10.0
    return r

然后我根据 Python 将 float 转换为字符串的内置功能测试了我的函数。不足为奇,我的函数在大数上有所不同。

>>> to_string(1e30)
'1000000000000000424684240284426'

>>> "%.f"%1e30
'1000000000000000019884624838656'

所以,我的问题是:我必须进行哪些计算才能获得 Python 获得的数字?

最佳答案

这是一个非常简单的解决方案。它不是为了提高效率或处理除正整数以外的任何值。

#!/usr/bin/python

import math

# This code represents a hexadecimal number using a list in which each item
# is a single hexadecimal digit (an integer from 0 to 15).

# Divide the base-16 digit-list in x by digit d.  This uses grade-school
# division, for a single-digit divisor.  It returns the quotient in a new
# digit-list and the remainder as a plain integer.
def Divide(x, d):

    # If the first digit is smaller than d, start an empty quotient with
    # a remainder being carried.
    if x[0] < d:
        q = []
        r = x[0]
    # Otherwise, start the quotient by dividing the first digit by d.
    else:
        q = [x[0] / d]
        r = x[0] % d

    # For the remaining digits, multiply the remainder by the base and
    # add the new digit.  Then divide by d, calculating a new digit of the
    # quotient and a new remainder to carry.
    for i in x[1:]:
        r = r*16 + i
        q.append(r/d)
        r = r % d

    return (q, r)

# Convert a positive integer floating-point value to decimal and print it.
def to_string(x):

    # Convert input to base 16.  This has no rounding errors since the
    # floating-point format uses base two, and 16 is a power of two.
    t= []
    while 0 < x:
        # Use remainder modulo 16 to calculate the next digit, then insert it.
        t.insert(0, int(x % 16))
        # Remove the digit from x.
        x = math.floor(x/16)

    # Start an empty output string.
    output = ""

    # Divide the number by 10 until it is zero (is an empty digit list).
    # Each time we divide, the remainder is a new digit of the answer.
    while t != []:
        (t, r) = Divide(t, 10)
        output = str(r) + output

    print output


to_string(1e30)

关于python - 如何编写 float -> string 并获得与 "%.f"相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48715957/

相关文章:

Python:条形图 - 垂直标签 - 剪切

python - 在 Django 中检索表单字段属性

python - 使用selenium webdriver爬取网页时,服务器如何区分是机器人还是人?

c - 无法使用 NEON Intrinsics 加载浮点值

c++ - float 和 double 变量中的数字

floating-point - 将带符号的单精度 float 舍入到最接近的整数的有效方法是什么?

objective-c - 将浮点值转换为 id。我怎样才能做到这一点?

Python 代码不读取 Travis CI 环境变量

Python Tkinter 将到达屏幕末尾的小部件包装在框架中

assembly - 释放 x87 FPU 堆栈 (ia32)