Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print floating point values without leading zero

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 leading zero in the format specifier. I couldn't find it in the docs.

Issue

>>> k = .1337 >>> print "%.4f" % k '0.1337' 

Hack

>>> print ("%.4f" % k) [1:] '.1337' 
like image 920
Paul Seeb Avatar asked Apr 24 '12 18:04

Paul Seeb


People also ask

How do I print float values without trailing zeros?

print( '{:,g}'. format( X ) worked for me to output 3 where X = 6 / 2 and when X = 5 / 2 I got an output of 2.5 as expected. old question, but.. print("%s"%3.140) gives you what you want.

How do you remove leading zeros from a decimal in Python?

If you want the final result to be an integer or a float, simply convert it after using int(out) or float(out) . Edit: if you want to change the precision (has to be fixed precision to account for trailing zeros), you just need to change the int appearing in the f-string: out = f'{x:.

How do you print numbers with leading zeros?

Use the str. zfill() Function to Display a Number With Leading Zeros in Python. The str. zfill(width) function is utilized to return the numeric string; its zeros are automatically filled at the left side of the given width , which is the sole attribute that the function takes.


1 Answers

Here is another way:

>>> ("%.4f" % k).lstrip('0') '.1337' 

It is slightly more general than [1:] in that it also works with numbers >=1.

Neither method correctly handles negative numbers, however. The following is better in this respect:

>>> re.sub('0(?=[.])', '', ("%0.4f" % -k)) '-.1337' 

Not particularly elegant, but right now I can't think of a better method.

like image 90
NPE Avatar answered Sep 21 '22 06:09

NPE