Jinja Literal Expression: Floats
n
.) as a decimal mark and can also be written in scientific notation using an uppercase or lowercase e to indicate the exponent. The underscore character (_) can be used to separate groups for improved legibility, but it cannot be used in the exponent part of a number.nn
nn
How It Works
nJinja2 recognizes any number with a decimal point or an exponent as a float. These are primarily used for calculations that require more precision than integers, such as averages, prices, or scientific values.n
Syntax
n
{{ 42.23 }}n{{ 42.1e2 }}n{{ 123_456.789 }}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use float literals in a Jinja2 application.n
1. Using Floats in Arithmetic
nThis demonstrates how floats are used to perform precise division, where the result is a number with a decimal part.nnJinja2 Templaten
{% set total_weight = 42.5 %}n{% set num_boxes = 5 %}n<p>Average weight per box: {{ total_weight / num_boxes }} kg</p>
nExplanation: The template divides the float `total_weight` by the integer `num_boxes`. The result will be a float (`8.5`), as the division operator (`/`) always returns a float.nn
nn
2. Scientific Notation
nThis example shows how to use scientific notation for very large or very small numbers.nnJinja2 Templaten
{% set avogadro_number = 6.022e23 %}n<p>Avogadro's number: {{ avogadro_number }}</p>
nExplanation: The float literal `6.022e23` is a shorthand for 6.022 multiplied by 10 to the power of 23. This is a common practice in scientific contexts to write large numbers concisely.nn
nn
3. Using Underscores with Floats
nThis example demonstrates how to use the underscore separator to improve the readability of a float.nnJinja2 Templaten
{% set large_number = 123_456_789.012_345 %}n<p>Large number with underscores: {{ large_number }}</p>
nExplanation: The underscores are ignored by the Jinja2 parser, so the output will be the full number `123456789.012345`. The underscores are purely a visual aid in the template code itself.nn
