Trying to use a format specifier to print a float that will be less than 1 without the leading zero. I came up with a bit of a hack but I assume there is a way to just drop
The problem is to print a float without the leading zero, regardless of the sign of the float. The leading zero always precedes a decimal point. Split the printed float on '0.', and then rejoin the resulting list around just '.', as in below:
>> flt = -.31415926
-0.31415926
>> '%.4f' % flt # prints leading zero
'-0.3142'
>> '.'.join( ('%.4f' % flt).split('0.')) # removes leading zero
'-.3142'
I'd rather go for readable and simple than anything else: Let's handle the sign and the numerics independently. And a little in-line if statement never hurt anyone.
k = -.1337
"".join( ["-" if k < 0 else "", ("%.4f" % abs(k)).lstrip('0')] )
As much as I like cute regex tricks, I think a straightforward function is the best way to do this:
def formatFloat(fmt, val):
ret = fmt % val
if ret.startswith("0."):
return ret[1:]
if ret.startswith("-0."):
return "-" + ret[2:]
return ret
>>> formatFloat("%.4f", .2)
'.2000'
>>> formatFloat("%.4f", -.2)
'-.2000'
>>> formatFloat("%.4f", -100.2)
'-100.2000'
>>> formatFloat("%.4f", 100.2)
'100.2000'
This has the benefit of being easy to understand, partially because startswith
is a simple string match rather than a regex.
One viable option which works without regex and with negative numbers greater than 10
k = -.1337
("%.4f" % k).replace("-0","-").lstrip("0")
Since we're only considering > -1 to < 1 then the following edit will work.
import re
re.sub(r"0+\.", ".", %0.4f" % k)
This will maintain the sign, only removing the digit to the left of the decimal.
I am surprised nobody suggested a more mathematical way to do it:
n = 0.123456789
'.%d' % (n*1e4)
Looks much nicer to me. :)
But interestingly yours is the fastest.
$ python -mtimeit '".%d" % (0.123456789*1e4)'
1000000 loops, best of 3: 0.809 usec per loop
$ python -mtimeit '("%.4f"%(0.123456789)).lstrip("0")'
1000000 loops, best of 3: 0.209 usec per loop
$ python -mtimeit '("%.4f"%(0.123456789))[1:]'
10000000 loops, best of 3: 0.0723 usec per loop