I am working with a library that uses int
for representing money amounts. For example, the following is what this looks like:
599
--> $5.99
500
--> $5.00
5
--> $0.05
0
--> $0.00
-599
--> $-5.99
I wrote the following function which does an exact float conversion without causing floating point errors, but what I am wondering is if I am approaching this the wrong way or if there is a much cleaner solution.
def money_int_to_float(value: int) -> float:
neg: str = '-' if value < 0 else ''
value = abs(value)
cents: int = value % 100
remaining: int = value - cents
dollars: int = int(str(remaining).removesuffix('00'))
return float(f'{neg}{dollars}.{str(cents).zfill(2)}')
My reasoning for wanting an exact float conversion is that when dealing with money you can never be too careful with floats.
source https://stackoverflow.com/questions/73365148/integer-float-exact-conversion-to-float
Comments
Post a Comment