簡體   English   中英

JavaScript toString(16) in Python 用於浮點數?

[英]JavaScript toString(16) in Python for floats?

我正在嘗試將以下 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM