使用AngularJS将数字限制为HTML文件中的2位小数

时间:2016-04-14 11:39:35

标签: javascript html angularjs web controller

我有一个HTML页面,显示AngularJS控制器的信息。这是代码的一部分:

<td id="calories">{{ ctrl.caltotal }}</td>

我的问题是,我需要做什么才能显示最多2个小数位?目前,如果我更改程序,它可以给出像23.00000004这样的值。这是应该在Angular Controller还是HTMl视图中进行的更改?感谢。

2 个答案:

答案 0 :(得分:3)

<td id="calories">{{ ctrl.caltotal | number:2}}</td>

这会将其限制为两位小数。

答案 1 :(得分:0)

请考虑以下代码:

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script> 
    <style>

    </style>
</head>
<body ng-app="myApp" ng-controller="myCtrl"> 
    <input type="number" ng-model="score" /> {{score | number:2}}
<script>
    //1 module declaration
    var app = angular.module('myApp', []);
    //2 controller declaration
    app.controller('myCtrl',function($scope){
        $scope.score = 50;
        //code here
    });
</script> 
</body> 
</html> 

请点击此处获取更多信息:

  

https://docs.angularjs.org/api/ng/filter/number

另见:

  

Angular how to display number always with 2 decimal places in <input>
  AngularJS {{ val | number:1 }} not rounding to 1 decimal place

相关问题