用于 float 的 Python 中的 JavaScript toString(16)?

标签 javascript python tostring

我正在尝试将以下 JavaScript 代码转换为 Python:

var n = 0.3846705659431655
n.toString(16)

result: "0.6279c52c75af6"
我现在面临的挑战是我似乎无法在 Python 中转换浮点数。它会对我产生错误或给我不同的结果。
示例:
n = 0.3846705659431655
float.hex(n)

result: 0x1.89e714b1d6bd8p-2
expected result: "0.6279c52c75af6"
有没有其他方法可以让我在 Python 中获得相同的结果?

最佳答案

我正在使用 Python 3.8 来做这件事,但它也应该适合你。

def FloatToHex(number, base = 16):
    if number < 0:                          # Check if the number is negative to manage the sign
        sign = "-"                          # Set the negative sign, it will be used later to generate the first element of the result list
        number = -number                    # Change the number sign to positive
    else:
        sign = ""                           # Set the positive sign, it will be used later to generate the first element of the result list

    s = [sign + str(int(number)) + '.']     # Generate the list, the first element will be the integer part of the input number
    number -= int(number)                   # Remove the integer part from the number

    for i in range(base):                   # Iterate N time where N is the required base
        y = int(number * 16)                # Multiply the number by 16 and take the integer part
        s.append(hex(y)[2:])                # Append to the list the hex value of y, the result is in format 0x00 so we take the value from postion 2 to the end
        number = number * 16 - y            # Calculate the next number required for the conversion

    return ''.join(s).rstrip('0')           # Join all the list values and return the converted number

n = 0.3846705659431655
print(FloatToHex(n))
结果0.6279c52c75af6

关于用于 float 的 Python 中的 JavaScript toString(16)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63537390/

相关文章:

javascript - 谷歌地图不显示标记

javascript - 无法显示 xml 文件的多个实体,但我可以显示一个

python - 如何在Python中使用groupby删除列表中的重复项?

java - 为嵌套类编写 toString 方法

javascript - Angular 7 共享服务不共享

单击时将 JavaScript 对象/数组值转换为表单输入

python - python 中的特征选择

python - 迭代 Django 中的相关对象

c# - 为什么在 ConfigurationManager.AppSettings[key] 上调用 .ToString()?

java - 覆盖 Arrays.toString() 方法