JavaScript toString(16) в Python для чисел с плавающей точкой?

#javascript #python #tostring

#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?

Комментарии:

1. Привет @cryptocake, добро пожаловать в SO! Какая версия Python?

2. Привет, @CarloZanocco, спасибо тебе! Я использую Python версии 3.7.5 в Windows.

Ответ №1:

Я делаю это с помощью 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