Restricting number to 2 decimal places in HTML file with AngularJS

被刻印的时光 ゝ 提交于 2019-12-12 02:53:48

问题


I have a HTML page that displays the information from an AngularJS controller. This is part of the code:

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

My question is, what do I need to do so that this is displayed at a maximum of 2 decimal places? At the moment if I change the program it can give values like 23.00000004. Is this a change that should be made in the Angular Controller or in the HTMl view? Thanks.


回答1:


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

That will restrict it to two decimal places.




回答2:


Consider the following code :

<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> 

See here for further information:

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

Also see:

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



来源:https://stackoverflow.com/questions/36621964/restricting-number-to-2-decimal-places-in-html-file-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!