Limited digits with str.format(), and then only when they matter

2024/11/14 12:49:30

If we're printing a dollar amount, we usually want to always display two decimal digits.

cost1, cost2 = 123.456890123456789, 357.000
print '{c1:.2f}  {c2:.2f}'.format(c1=cost1, c2=cost2)

shows

123.46  357.00

But on other occasions we'd like to print the fractions only if they matter. If the two numbers above were volume, for instance, we may prefer to display

123.45 gal. 357 gal.

Can this be obtained directly with format?

Answer

In String Formatting Operations Python Docs describe the %g format which truncates trailing zeros.

>>> print "%g gallons" % (123.45)
123.45 gallons>>> print "%g gallons" % (357)
357 gallons>>> print "%g gallons" % (357.0)
357 gallons

Or using Python 3 string formatting:

>>> print "{:g} gal {:g} gal".format(123.45, 357.0)
123.45 gal 357 gal

The g formatter is unintuitive but you can get some interesting results by setting the precision:

>>> print "{:g} gal {:.3g} gal {:.4g} gal {:.5g} gal {:.6g} gal {:.7g} gal".format(*([123.456789] * 6))
123.457 gal 123 gal 123.5 gal 123.46 gal 123.457 gal 123.4568 gal

Note that in this case setting precision to .5 achieves the desired result of 2 decimal places.

Of course you could combine this with f floating point formatter first to get whatever you wanted.

https://en.xdnf.cn/q/119363.html

Related Q&A

How is covariance implemented internally in numpy?

This is the definition of a covariance matrix. http://en.wikipedia.org/wiki/Covariance_matrix#DefinitionEach element in the matrix, except in the principal diagonal, (if I am not wrong) simplifies to E…

Pulling excel rows to display as a grid in tkinter

I am imaging fluorescent cells from a 384-well plate and my software spits out a formatted excel analysis of the data (16 rowsx24 columns of images turns into a list of data, with 2 measurements from e…

Django Migrating DB django.db.utils.ProgrammingError: relation django_site does not exist

Doing a site upgrade for Django, now pushing it to the server when I try python manage.py makemigrations I get this error (kpsga) sammy@kpsga:~/webapps/kpsga$ python manage.py makemigrations Traceback …

list intersection algorithm implementation only using python lists (not sets)

Ive been trying to write down a list intersection algorithm in python that takes care of repetitions. Im a newbie to python and programming so forgive me if this sounds inefficient, but I couldnt come …

In keras\tensorflow, How adding CNN layers to last layer of ResNet50V2 that pre-train on imagenet

I am trying to drop the last layer and add a simple CNN instead like the following, model = Sequential() base_model = ResNet50V2(include_top=False, weights="imagenet", input_shape=input_shape…

How to get missing date in columns using python pandas [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 3 years ago.Improve…

vigenere cipher - not adding correct values

I want to get specific values from a for loop to add to another string to create a vigenere cipher.heres the code.userinput = input(enter message) keyword = input(enter keyword) new = for a in keyword…

Why isnt my output returning as expected?

So I wrote this code def diagsDownRight(M):n = len(M)m = [[] * (n - i - 1) + row + [] * i for i, row in enumerate(M)]return ([.join(col) for col in zip(*m)]), [.join(col[::-1]) for col in zip(*m)] def …

Django Stripe payment does not respond after clicking the Submit Payment button

I have an e-commerce application that Im working on. The app is currently hosted on Heroku free account. At the moment I can select a product, add it on the cart and can get up to the stripe form and t…

get file path using backslash (\) in windows in python [duplicate]

This question already has answers here:How can I put an actual backslash in a string literal (not use it for an escape sequence)?(4 answers)Closed 2 years ago.How to get result exactly the same format…