support scientific notation

This commit is contained in:
CleoQc 2018-11-12 13:56:41 -05:00 committed by David Lord
parent 626bdd08d4
commit fd00805ca7
No known key found for this signature in database
GPG Key ID: 7A1C87E3F5BC42A8
3 changed files with 21 additions and 6 deletions

View File

@ -1177,12 +1177,19 @@ for Python objects such as strings and numbers. The following literals exist:
arguments to function calls and filters, or just to extend or include a
template).
42 / 42.23:
Integers and floating point numbers are created by just writing the
number down. If a dot is present, the number is a float, otherwise an
42:
Integers numbers are created by just writing the number down.
If a dot is present, the number will be considered a float, otherwise an
integer. Keep in mind that, in Python, ``42`` and ``42.0``
are different (``int`` and ``float``, respectively).
42.23 / 42e2 / 42E2 / 1e0:
Floating point numbers are created by just writing the
number down. Floating points can be written using the dot as a decimal mark,
or they can be written in scientific notation in which
case you can use lower case 'e' or upper case 'E' to indicate the exponent
part.
['list', 'of', 'objects']:
Everything between two brackets is a list. Lists are useful for storing
sequential data to be iterated over. For example, you can easily

View File

@ -22,6 +22,8 @@ from jinja2._compat import implements_iterator, intern, iteritems, text_type
from jinja2.exceptions import TemplateSyntaxError
from jinja2.utils import LRUCache
from ast import literal_eval # to support scientific notation
# cache for the lexers. Exists in order to be able to have multiple
# environments with the same lexer
_lexer_cache = LRUCache(50)
@ -52,7 +54,11 @@ else:
del jinja2._identifier
del _identifier
float_re = re.compile(r'(?<!\.)\d+\.\d+')
# Note: Float now supports 0 or 1 dots, and must thus be evaluated in the right
# order so that pure integers are caught first. Floats can now be written with
# scientific notation.
float_re = re.compile(r'(?<!\.)\d+\.?\d+(?:e-?\d+)?', re.IGNORECASE)
newline_re = re.compile(r'(\r\n|\r|\n)')
# internal the tokens and keep references to them
@ -601,7 +607,7 @@ class Lexer(object):
elif token == 'integer':
value = int(value)
elif token == 'float':
value = float(value)
value = literal_eval(value)
elif token == 'operator':
token = operators[value]
yield Token(lineno, token, value)

View File

@ -136,9 +136,11 @@ class TestFilter(object):
def test_float(self, env):
tmpl = env.from_string('{{ "42"|float }}|'
'{{ "ajsghasjgd"|float }}|'
'{{ "10e1"|float }}|'
'{{ "10.5e-10"|float }}|'
'{{ "32.32"|float }}')
out = tmpl.render()
assert out == '42.0|0.0|32.32'
assert out == '42.0|0.0|100.0|1.05e-09|32.32'
def test_format(self, env):
tmpl = env.from_string('''{{ "%s|%s"|format("a", "b") }}''')