5
>>> "{: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.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Sumanth
  • 198
  • 1
  • 5
  • 1
    My guess is this has to do with how `float`s are represented in memory and what the closest `float` value is to the "real" result. – Code-Apprentice Aug 30 '22 at 17:29
  • 1
    You might want to read more about how floating point math works in general. https://stackoverflow.com/questions/588004/is-floating-point-math-broken is a good place to start. – Code-Apprentice Aug 30 '22 at 17:31
  • Sidenote: this can be done using f-strings. `f"{214929/2:g}"` – Chris Aug 30 '22 at 17:45

2 Answers2

6

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

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

Torin M.
  • 523
  • 1
  • 7
  • 26
  • 2
    You can also find this in the official docs, [here](https://docs.python.org/3/library/string.html#format-specification-mini-language). – Blckknght Aug 30 '22 at 17:42
0

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
dawg
  • 98,345
  • 23
  • 131
  • 206