Dev
Dev

Reputation: 1921

Angular ng-model expression

I want to ask how can I round the numbers inside an input, using angularjs

<input type="number" ng-model="value1"/>

I want the number to show 2 decimals with rounding.

Can you help please

Upvotes: 2

Views: 1590

Answers (2)

Kevin F
Kevin F

Reputation: 2885

You can use ng-change:

<input type="number" ng-model="value1" ng-change="roundNumber()" />

$scope.roundNumber = function(){
    $scope.value1 = Math.round($scope.value1 * 100) / 100;
};

//call function once at bottom of controller for initial run
$scope.roundNumber();

Or create a directive to do it if this is going to be a common functionality you want

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

Use $watch in this case will be more appropriate, It will tend to format value on initial load also.

Markup

<input type="number" ng-model="value1"/>

Code

$scope.$watch('value1',function(newVal, oldVal){
    if((newVal != oldVal))
       $scope.value1 = newVal?  newVal.toFixed(2): 0;
});

Upvotes: 1

Related Questions