Home > database >  Why is python format function rounding off certain numbers but not others?
Why is python format function rounding off certain numbers but not others?

Time:08-31

>>> "{:g}".format(float(214929)/2)                                                                                      
    '107464'  
>>> "{:g}".format(float(105793)/2)                                                                                      
    '52896.5' 

I'm trying to print certain numbers in decimal format for small numbers and in scientific notation for large ones.

Why is the format function rounding off certain float divisions to the nearest integers but not others? What am I missing here? I have tried both python2 and 3.

CodePudding user response:

"g" formatting specifier defaults to rounding to 6 significant figures.

https://python-reference.readthedocs.io/en/latest/docs/str/formatting.html

CodePudding user response:

Since you have a more complex need (decimal for small, scientific for large) you may want to subclass a float to control its output presentation more tightly.

An example:

class MyF(float):
    def __init__(self, x, dec=2, tos=1e6):
        self.val=float(x)
        self.dec=dec 
        self.tos=tos
        
    def __repr__(self):
        if abs(self.val)>self.tos:
            return f"{self.val:g}"
        return f"{self.val:,.2f}"

Test that:

cases=(float(214929)/2, float(105793)/2, 123456789/2, 1)
for e in cases:
    print(f"{e:12} {e:12g}\t", MyF(e))

Prints:

    107464.5       107464    107,464.50
     52896.5      52896.5    52,896.50
  61728394.5  6.17284e 07    6.17284e 07
           1            1    1.00
  • Related