faqts : Computers : Programming : Languages : Python : Snippets : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 5 people (60%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

Cutting off trailing zeroes

Jul 5th, 2000 10:03
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 369, Carel Fellinger


"""
Packages: text.formatting
"""
"""
> Id like to format a string like this:
>   s = "(%f)" % x
> Now if x=1.5 then s="1.50000" or something like this. Is there a tirivial
> way of cutting of the zeroes, i.e. getting s="1.5" instead of s="1.50000"?
try the g and G specifiers like:
"""
print "%g" % 1.5000
# 1.5
print "%g" % 1.50002
# 1.50002
print "%1.3g" % 1.50002
#1.5
"""
the default precision for g is, I think, .8. But it doesn't quit work
like
advertised (on my system at least), somehow it influences the field
width
as wel:( So you get 8 chars atmost, including the point and the numbers
before the point. So be carefull to avoid the following:
"""
print "%1.3g" % 111.50002
# 112