Anderson P
Anderson P

Reputation: 107

Error When Double Unpacking Number

I have some code that looks like:

import struct

def Get_Float(paintwear):
    buf = struct.pack('i', paintwear)
    item_float = struct.unpack('f', buf)[0]
    return item_float

paintwear = 1033975072
item_float = Get_Float(paintwear)
print(item_float)

This works and gives me item_float as 0.07871460914611816. However, I am trying to get that number to be more specific by double unpacking it like this:

import struct

def Get_Float(paintwear):
    buf = struct.pack('i', paintwear)
    item_float = struct.unpack('d', buf)[0]
    return item_float

paintwear = 1033975072
item_float = Get_Float(paintwear)
print(item_float)

I changed the f to a d and now I get this error: struct.error: unpack requires a bytes object of length 8

Any ideas? Thanks!

Upvotes: 2

Views: 108

Answers (1)

l'L'l
l'L'l

Reputation: 47169

Use floating point number formatting:

return "{:.22f}".format(item_float)

Where 22 is the number of digits returned (or however many required) after the decimal.

Upvotes: 1

Related Questions