如何在Javascript / Angular JS中进行舍入 - 但删除无关紧要的数字 [英] How to round in Javascript/Angular JS -- but remove insignificant digits
问题描述
我的Javascript控制器中有以下语句:
I have a the following statement in my Javascript controller:
$scope.myList = [0, 1, 0.5, 0.6666666];
我的AngularJS模板包括以下内容:
My AngularJS template includes has the following in it:
<div ng-repeat="i in myList">{{i}}</div>
这会产生以下HTML输出:
This produces the following HTML output:
<div>0</div>
<div>1</div>
<div>0.5</div>
<div>0.6666666</div>
但是,我希望将数字四舍五入到小数点后两位。 但是,我想在输出中只看到有效数字。我不希望看到尾随零。我该怎么做?使用 {{i |数字:2}}
不会消除尾随零。
However, I want the numbers to be rounded to 2 decimal places. However, I would like to see only significant digits in the output. I don't want to see trailing zeroes. How do I do it? Using {{i | number:2}}
doesn't eliminate trailing zeroes.
推荐答案
你可以只乘以1将其转换为真值。
You could just multiple by 1 to convert it to true value.
<div ng-repeat="i in myList">{{(i | number:2)*1}}</div>
从上面的评论中可以看出,解决方案会因角色数过滤器的区域设置格式而中断。如果您需要区域设置格式和舍入,您可以创建一个扩展过滤器,下面使用数字过滤器
和 $ locale
服务。
As noted from the comments above solution will break due to the locale formatting by angular number filter. If you need the locale formatting and rounding you could create an extension filter which underneath uses number filter
and $locale
service.
.filter('numberEx', ['numberFilter', '$locale',
function(number, $locale) {
var formats = $locale.NUMBER_FORMATS;
return function(input, fractionSize) {
//Get formatted value
var formattedValue = number(input, fractionSize);
//get the decimalSepPosition
var decimalIdx = formattedValue.indexOf(formats.DECIMAL_SEP);
//If no decimal just return
if (decimalIdx == -1) return formattedValue;
var whole = formattedValue.substring(0, decimalIdx);
var decimal = (Number(formattedValue.substring(decimalIdx)) || "").toString();
return whole + decimal.substring(1);
};
}
]);
并将其用作:
<div ng-repeat="i in myList">{{i | numberEx:2}}</div>
演示
angular.module('app', []).controller('ctrl', function($scope) {
$scope.myList = [0, 10000.56, 0.5, 0.6666666, -1000.23123, 1, 1002, 2.5, 30.5, 22];
}).filter('numberEx', ['numberFilter', '$locale',
function(number, $locale) {
var formats = $locale.NUMBER_FORMATS;
return function(input, fractionSize) {
//Get formatted value
var formattedValue = number(input, fractionSize);
//get the decimalSepPosition
var decimalIdx = formattedValue.indexOf(formats.DECIMAL_SEP);
//If no decimal just return
if (decimalIdx == -1) return formattedValue;
var whole = formattedValue.substring(0, decimalIdx);
var decimal = (Number(formattedValue.substring(decimalIdx)) || "").toString();
return whole + decimal.substring(1);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div ng-repeat="i in myList">{{i | numberEx:2}}</div>
</div>
这篇关于如何在Javascript / Angular JS中进行舍入 - 但删除无关紧要的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!