I have an API that serves data in JSON which includes a lot of decimal/float numbers. It so hapens that a lot of these numbers are between 0 and 1, and can sometimes be quite small... small enough that they were occasionally being represented in scientific notation (e.g. 0.00025
was represented as 2.5e-05
). I needed a way to prevent the API from ever serving up numbers in scientific notation, so I wrote this utility function as part of a JSONEncoder for all float numbers:
def format_float(self):
return f"{self:.16f}".rstrip("0").rstrip(".")
That way, it would first change a number like 0.000025
to 0.0000250000000000
, then strip the trailing zeroes, leaving the number represented as I'd like to see it. And for whole numbers like -1
, the formatting was likewise benign, as it removes the trailing zeroes and trailing period.
But I run into a problem with numbers like 1.4
. Run that through my function, and it is now represented as 1.3999999999999999
. Is there some way I can tweak this to ensure it properly rounds up in situations like this?