How do you round to 1 decimal place in Javascript?

前端 未结 21 1804
难免孤独
难免孤独 2020-11-22 08:49

Can you round a number in javascript to 1 character after the decimal point (properly rounded)?

I tried the *10, round, /10 but it leaves two decimals at the end of

21条回答
  •  天涯浪人
    2020-11-22 08:57

    Little Angular filter if anyone wants it:

    angular.module('filters').filter('decimalPlace', function() {
        return function(num, precision) {
            var multiplier = Math.pow(10, precision || 0);
            return Math.round(num * multiplier) / multiplier;
        };
    });
    

    use if via:

    {{model.value| decimalPlace}}
    {{model.value| decimalPlace:1}}
    {{model.value| decimalPlace:2}}
    

    :)

提交回复
热议问题