How to round in Javascript/Angular JS — but remove insignificant digits

前端 未结 3 1623
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-18 21:49

I have a the following statement in my Javascript controller:

$scope.myList = [0, 1, 0.5, 0.6666666];

My AngularJS template contains the follow

3条回答
  •  礼貌的吻别
    2021-02-18 22:22

    As the other answers didn't really work well, or did not not incorporate or work with Angular's $locale service, I wrote the following filter:

    Template:

    {{yourNumber | roundTo: N}}
    

    Filter:

    app.filter('roundTo', function(numberFilter) {
        return function(value, maxDecimals) {
            return numberFilter((value || 0)
                .toFixed(maxDecimals)
                .replace(/(?:\.0+|(\.\d+?)0+)$/, "$1")
            );
        }
    })
    

    • Rounds the number to the max number of decimals

    • Trims all trailing zero's

    • Removes the decimal seperator when it's not needed

    • And Uses Angular's $locale formatting

提交回复
热议问题