树枝:如何围捕?

问题描述 投票:10回答:8

我在树枝上有一个部门。有时,结果可能是小数,我需要总是一个舍入结果。

防爆。

7 / 2 = 3.5

我想拥有

7 / 2 = 4

我知道如何在树枝上使用地板:

7 / 2 | floor = 3

但这是向下数字,而不是向上数字。

我也知道我可以使用number_format

7 / 2 | number_format(0, '.', ',') = 3

所以这也将采取下降数字。

关于如何告诉树枝采取高位数的任何想法?

这可以在控制器(Symfony)中完成,但我正在寻找树枝版本。

谢谢。

php symfony twig number-formatting
8个回答
14
投票

Update

在1.15.0+版本上,可以使用round过滤器。

{{ (7 / 2)|round(1, 'ceil') }}

http://twig.sensiolabs.org/doc/filters/round.html


您可以扩展树枝并编写自定义函数,如here所述

它将是这样的:

<?php
// src/Acme/DemoBundle/Twig/AcmeExtension.php
namespace Acme\DemoBundle\Twig;

class AcmeExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            'ceil' => new \Twig_Filter_Method($this, 'ceil'),
        );
    }

    public function ceil($number)
    {
        return ceil($number);
    }

    public function getName()
    {
        return 'acme_extension';
    }
}

所以你可以在树枝上使用它:

7 / 2 | ceil

10
投票

版本1.15.0中的新功能:在Twig 1.15.0中添加了圆形过滤器。

示例:{{ 42.55|round(1, 'ceil') }}

圆形过滤器有两个可选参数;第一个指定精度(默认为0),第二个指定舍入方法(默认为常用)

http://twig.sensiolabs.org/doc/filters/round.html


4
投票

不知道它在以前的版本中是怎么回事,但在Symfony 2.2.1中你必须在计算周围使用括号(假设你创建了扩展名):

(7 / 2)|ceil

显然7 / 2|ceil7 / (2|ceil)相同,因为他们都给出了相同(错误)的结果,只有上述解决方案适合我。


2
投票

你试过7 // 2吗?

这个documentation page可能有用。


2
投票

http://twig.sensiolabs.org/doc/filters/round.html

从Twig 1.15.0开始,您可以使用'round'过滤器并将'ceil'作为第二个参数传递。解决方案如下所示:

{{ (7 / 2)|round(0, 'ceil') }}

格式化显示的数字肯定属于视图,而不是控制器。这将被视为显示逻辑 - 这与控制器中的业务逻辑不同,应尽可能保持最小化。


0
投票

如果您使用的是版本1.12.0或更高版本,则可以使用三元运算符并执行以下操作:

{{ ((7 / 2) > (7 // 2)) ? (7 // 2) + 1 : (7 // 2) }}

它不是那么“优雅”,但无论如何都有效。


0
投票

圆形过滤器将第一个参数作为精度。因此,回答OP问题的正确方法是:

{{ (7 / 2)|round(0, 'ceil') }}

而不是

{{ (7 / 2)|round(1, 'ceil') }}

http://twig.sensiolabs.org/doc/filters/round.html


-3
投票

http://php.net/manual/en/function.ceil.php

使用php的上限功能来做你想要的

© www.soinside.com 2019 - 2024. All rights reserved.