Is there a way to specify to format I want a floating point written with no more than e.g., 2 digits after the decimal? I tried {:.2f}, but then I get all floats written with 2 digits, even if they are 0:
2.35 << yes, that's what I want
2.00 << no, I want just 2 or 2.
On Mon, Oct 15, 2012 at 5:12 AM, Neal Becker <ndbeck...@gmail.com> wrote:
> Is there a way to specify to format I want a floating point written with no more
> than e.g., 2 digits after the decimal? I tried {:.2f}, but then I get all
> floats written with 2 digits, even if they are 0:
> 2.35 << yes, that's what I want
> 2.00 << no, I want just 2 or 2.
Not that I can find. Seems you'll have to implement it yourself.
> Is there a way to specify to format I want a floating point written with no more
> than e.g., 2 digits after the decimal? I tried {:.2f}, but then I get all
> floats written with 2 digits, even if they are 0:
> 2.35 << yes, that's what I want
> 2.00 << no, I want just 2 or 2.
Maybe you're looking for "{:.3g}"
print "{:.3g}".format(2)
# '2'
print "{:.3g}".format(2.00)
# '2'
print "{:.3g}".format(2.35)
# '2.35'
print "{:.3g}".format(2.356) # this rounds up
# '2.36'
> On Mon, Oct 15, 2012 at 5:12 AM, Neal Becker <ndbeck...@gmail.com> wrote:
>> Is there a way to specify to format I want a floating point written with no more
>> than e.g., 2 digits after the decimal? I tried {:.2f}, but then I get all
>> floats written with 2 digits, even if they are 0:
>> 2.35 << yes, that's what I want
>> 2.00 << no, I want just 2 or 2.
> Not that I can find. Seems you'll have to implement it yourself.
To do it yourself, probably best to use a temp string value, created by
format "{: f}". (Notice the space before the f, to reserve space for
the sign) Then, slice that value to length 4 . Finally, in your actual
format, use :5s for a format. This should add the blanks for padding,
so other columns still line up.
The precision is a decimal number indicating how many digits
should be displayed after the decimal point for a floating
point value formatted with 'f' and 'F', or before and after the
decimal point for a floating point value formatted with 'g' or
'G'. For non-number types the field indicates the maximum field
size - in other words, how many characters will be used from
the field content. The precision is not allowed for integer
values.
So g will print a specific number of significant digits, so it
won't do what Adrien wants.
And f will print a fixed number of digits after the decimal
point, so it won't do want Adrien wants.
Adrien, you will need to do some post-processing on fixed point
output to remove trailing zeroes.