I’ll settle this .
round()
was the obvious way to do this, and anything else is gratuitous complication. It would be more useful to point out that converting to a little-endian byte string “by hand” is much easier done like so - which also has the benefit that it will raise an exception (unlike the original code) if the input is “too big” to represent in 4 bytes:
>>> def pennies(x):
... return round(x * 100).to_bytes(4, "little")
>>> pennies(4.05).hex()
'95010000'
>>> pennies(3.05).hex()
'31010000'
>>> pennies(2.05).hex()
'cd000000'
>>> pennies((2**32 - 1) / 100).hex()
'ffffffff'
>>> pennies(2**32 / 100).hex()
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
pennies(2**32 / 100).hex()
File "<pyshell#60>", line 2, in pennies
return round(x * 100).to_bytes(4, "little")
OverflowError: int too big to convert