Thomas Mattinzioli
Thomas Mattinzioli

Reputation: 3

How do you format numbers called from an API in Django?

I have some values called from an API in a course I'm doing which I would like to format improve visibility. What is the best way to code this? Thanks. Example code is below:

${{list_item.marketCap}} {{list_item.ytdChange}}%

Where, the first one I would like to add a comma for thousands and 2dp, and the second times by 100?

Upvotes: 0

Views: 187

Answers (2)

HubertBlu
HubertBlu

Reputation: 829

You can change the first one to 2dp with a comma like so...

 {{  "{:,.2f}".format(float(list_item.marketCap))  }}

And to get the second item * 100 you simply return...

 {{  float(list_item.ytdChange) * 100 }}

Hopefully that works for you!

Upvotes: 2

Frederic Perron
Frederic Perron

Reputation: 798

There are two options that I would suggest:


  1. You either want to make a new template tag that formats your Django variable. The template tag will simply be a function created by you taking your variable into account and return the formatted value.

  1. The second option consist of formatting the variables before the view is rendered and add it in the context of the render view return statement.

For the format function, there is nothing really complicated here. You can just use string concatenation or the Python String Interpolation.

Here's an example:

def format_thousands(value):
    return f'{value:,}' # Using Python ≥3.6

def format_two_decimals(value):
    return round(value, 2)

For more information on context and views, please refer to the Django Doc since it is the basic stuff not related to that question.

Upvotes: 0

Related Questions