How to display fractions in Django
Short post about rendering for example 1/4, 1/2 and other fractions in your Django template. Turns out this is not complicated if you know about important parts to combine.
Published: July 25, 2020 Sponsored App StoreFor the first time I guess ever I needed to display fractions in my Django template. Meaning stuff like 1/4 to represent 0.25 or 25%. This has basically two parts.
- Get fraction from number
- Render this fraction in HTML
Let's start with our Python code. Turns out there is handy module named fractions
. We are going to just scratch its surface and use the type Fraction
so start with this import:
from fractions import Fraction
The usage is beautifully simple. We can just initialize Fraction
with number and then print
the result to get the fraction:
f1 = Fraction(0.5)
print(f1)
The result will be 1/2
. Without any extra work. We could use this in our template but HTML provides better way of actually displaying and properly rendering the fraction.
In my use case I chose to send the whole Fraction
object into my template to render it there.
HTML offers tags <sup>
and <sub>
to display text raised and lowered respectively. The former is frequently used for math equations and similar stuff. We can combine both with /
to have pretty fractions.
The basic markup looks like this:
<sup>1</sup>⁄<sub>2</sub>
This will get you very nice looking "1/2".
The last step is to actually use our Fraction
object:
<sup>{{ fraction.numerator }}</sup>⁄<sub>{{ fraction.denominator }}</sub>
Numerator is the "top" number while denominator is the "bottom" number. I have to admit I had to google how is the "numerator" called.