* 1.15.0 (2013-XX-XX)
+ * added the round filter
* fixed the C extension sandbox behavior when get or set is prepend to method name
* 1.14.2 (2013-10-30)
raw
replace
reverse
+ round
slice
sort
split
--- /dev/null
+``round``
+=========
+
+.. versionadded:: 1.15.0
+ The ``round`` filter was added in Twig 1.15.0.
+
+The ``round`` filter rounds a number to a given precision:
+
+.. code-block:: jinja
+
+ {{ 42.55|round }}
+ {# outputs 43 #}
+
+ {{ 42.55|round(1, 'floor') }}
+ {# outputs 42.5 #}
+
+The ``round`` filter takes two optional arguments; the first one specifies the
+precision (default is ``0``) and the second the rounding method (default is
+``common``):
+
+* ``common`` rounds either up or down (rounds the value up to precision decimal
+ places away from zero, when it is half way there -- making 1.5 into 2 and
+ -1.5 into -2);
+
+* ``ceil`` always rounds up;
+
+* ``floor`` always rounds down.
+
+.. note::
+
+ The ``//`` operator is equivalent to ``|round(0, 'floor')``.
+
+Arguments
+---------
+
+* ``precision``: The rounding precision
+* ``method``: The rounding method
* ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is
``4``.
-* ``//``: Divides two numbers and returns the truncated integer result. ``{{
- 20 // 7 }}`` is ``2``.
+* ``//``: Divides two numbers and returns the truncated integer result. ``{{ 20
+ // 7 }}`` is ``2`` (this is just syntactic sugar for the
+ :doc:`round<filters/round>` filter).
* ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would
return ``4``.
new Twig_SimpleFilter('replace', 'strtr'),
new Twig_SimpleFilter('number_format', 'twig_number_format_filter', array('needs_environment' => true)),
new Twig_SimpleFilter('abs', 'abs'),
+ new Twig_SimpleFilter('round', 'twig_round'),
// encoding
new Twig_SimpleFilter('url_encode', 'twig_urlencode_filter'),
}
/**
+ * Rounds a number.
+ *
+ * @param integer|float $value The value to round
+ * @param integer|float $precision The rounding precision
+ * @param string $method The method to use for rounding
+ *
+ * @return integer|float The rounded number
+ */
+function twig_round($value, $precision = 0, $method = 'common')
+{
+ if ('common' == $method) {
+ return round($value, $precision);
+ }
+
+ if ('ceil' != $method && 'floor' != $method) {
+ throw new Twig_Error_Runtime('The round filter only supports the "common", "ceil", and "floor" methods.');
+ }
+
+ return $method($value * pow(10, $precision)) / pow(10, $precision);
+}
+
+/**
* Number format filter.
*
* All of the formatting options can be left null, in that case the defaults will
--- /dev/null
+--TEST--
+"round" filter
+--TEMPLATE--
+{{ 2.7|round }}
+{{ 2.1|round }}
+{{ 2.1234|round(3, 'floor') }}
+{{ 2.1|round(0, 'ceil') }}
+
+{{ 21.3|round(-1)}}
+{{ 21.3|round(-1, 'ceil')}}
+{{ 21.3|round(-1, 'floor')}}
+--DATA--
+return array()
+--EXPECT--
+3
+2
+2.123
+3
+
+20
+30
+20