0

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?

soapergem
  • 9,263
  • 18
  • 96
  • 152
  • Why do you need to prevent it? Is it possible to change the client which accepts the API input? – Banana Apr 02 '20 at 13:16
  • Why does the first comment of every question asked on Stack Overflow always have to question _why_ the questioner is doing something in the way they've described, rather than just addressing the question at hand? This happens **every** single time. Comments like that make the experience on Stack Overflow genuinely draining as it is essentially off-topic. I should not have to explain my motivations every single time I'm asking a relatively simple question. Suffice it to say that I cannot change the client; that is out of my control. – soapergem Apr 02 '20 at 13:27
  • I'm sorry but often people ask for something difficult and there's something easier they could have done, the so-called XY-Problem. – Banana Apr 02 '20 at 13:32

0 Answers0