AngularJS中的数字向下舍入

时间:2017-11-07 19:49:13

标签: angularjs rounding

是否有任何内置方法可以将数字向下舍入而不管小数位数?

例如

<div>{{var / 3 | number:0}}</div>

如果除法的结果是9.99我想只显示9,而不是10

由于

2 个答案:

答案 0 :(得分:3)

使用自定义过滤器,这是一个很好的答案:http://tianes.logdown.com/posts/2015/12/08/rounding-a-number-to-the-nearest-neighbour-up-and-down

/*********************************************************
    - Author: Sebastian Cubillos
    - Github: @tianes
    - More Gists: https://gist.github.com/tianes/
    - Contact: sebastian@cubillos.org
    - Article: http://tianes.logdown.com/posts/2015/12/08/rounding-a-number-to-the-nearest-neighbour-up-and-down
**********************************************************/

app.filter('round', function () {
    /* Use this $filter to round Numbers UP, DOWN and to his nearest neighbour.
       You can also use multiples */

    /* Usage Examples:
        - Round Nearest: {{ 4.4 | round }} // result is 4
        - Round Up: {{ 4.4 | round:'':'up' }} // result is 5
        - Round Down: {{ 4.6 | round:'':'down' }} // result is 4
        ** Multiples
        - Round by multiples of 10 {{ 5 | round:10 }} // result is 10
        - Round UP by multiples of 10 {{ 4 | round:10:'up' }} // result is 10
        - Round DOWN by multiples of 10 {{ 6 | round:10:'down' }} // result is 0
    */
    return function (value, mult, dir) {
        dir = dir || 'nearest';
        mult = mult || 1;
        value = !value ? 0 : Number(value);
        if (dir === 'up') {
            return Math.ceil(value / mult) * mult;
        } else if (dir === 'down') {
            return Math.floor(value / mult) * mult;
        } else {
            return Math.round(value / mult) * mult;
        }
    };
});

答案 1 :(得分:1)

你可以使用javascripts Floor()将数字向下舍入到最接近的整数

var numb = Math.floor(9.99) // numb = 9