Formatting floating point

Chris Angelico rosuav at gmail.com
Wed Sep 4 13:25:55 EDT 2019


On Thu, Sep 5, 2019 at 3:16 AM Dave via Python-list
<python-list at python.org> wrote:
>
> All,
>
> I have been going in circles trying to format a floating point number so
> there is only 1 decimal place.  In reading all of the gobble-gook that
> passes for Python advice, it looked like I should have done this:
>
> numStr = '3.14159'
> num = float(numstr)     # OK so far
> numFmt = format(num, '{0:.1f}')         # Errors on format string
> # --- Alternative that also does not work
> numFmt = float("{0:.1f}".format(numStr))
> # ---
> numFmt = format(num, '0.1f')            # Does work
>

Let's start by eliminating a few possibilities here. Don't try
formatting the original string, and don't call float() on the result
afterwards; just start with a floating-point value, and then create a
formatted string. If you think about starting with a value (which in
this case is a number) and the need to make a displayable version
(which implies that it's a string), your options basically look like
this:

num = 3.14159
num_fmt = format(num, ".1f")
num_fmt = "{0:.1f}".format(num)
num_fmt = f"{num:.1f}"

All of these will give you back the string "3.1". All of them involve
a format string of ".1f", and they differ only in how they're choosing
which value to put there.

Hopefully that will clear things up a bit.

ChrisA



More information about the Python-list mailing list