Cambium Cambium - 6 months ago 16
Python Question

How to define a new string formatter

I often use this small function

especially to show big or small numbers in an easy to read way.

This allows me to write
"%e" % (number)
.

I would like to be able to write
"%n" % (number)
and get the number formatted by this
eng(x)
function.

Is there a way to do this?

Answer

You can implement a new number class:

from math import floor, log10
class snumber(float):
        def powerise10(x):
            if x == 0: return 0 , 0 
            Neg = x <0
            if Neg : x = -x
            a = 1.0 * x / 10**(floor(log10(x)))
            b = int(floor(log10(x)))
            if Neg : a = -a
            return a ,b

        def __str__(x):
            a , b = snumber.powerise10(x)
            if -3<b<3: return "%.4g" % x 
            a = a * 10**(b%3)
            b = b - b%3 
            return "%.4g*10^%s" %(a,b)

print "{}".format(snumber(100000))

Gives:

100*10^3