1

I want to bind input value 0.00 to text box then, if I changed input to 20 then on blur set 20.00

<input type="text" valid-decimal-number style="text-align:right"  ng-model="Amount"  ng-blur="ConvertToDecimal(Amount)">

angular script :

//converting value to decimal
$scope.ConvertToDecimal = function (val) {
   $scope.Amount = eval(val).toFixed(2);
}

I am getting by using this code but, for every time I'm writing, how to create custom directive for this

I tried like this also but not working.

<input type="text" valid-decimal-number style="text-align:right"  ng-model="Amount"  ng-blur="'Amount=(Amount).toFixed(2)'">
2
  • 1
    Remove ' from ng-blur Commented Aug 8, 2017 at 9:05
  • i have tried removing that also, text box becoming empty after blur event Commented Aug 8, 2017 at 9:08

2 Answers 2

1

use a filter in ng-blur

ng-blur="Amount = (Amount | number : 2 )" 

Demo

angular.module("app",[])
.controller("ctrl",function($scope){


})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <input type="text" style="text-align:right"  ng-model="Amount" ng-blur="Amount = (Amount | number : 2 )" >

</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sachila , its worked.Is it possible to create custom directive for this
1

You can apply toFixed(2) to numbers only

<html ng-app="myApp">
<head>
	<title></title>
</head>
<body ng-controller="myCtrl">
<input type="text" valid-decimal-number style="text-align:right"  ng-model="Amount"  ng-blur="ConvertToDecimal()">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller('myCtrl', ['$scope', function ($scope) {
$scope.ConvertToDecimal = function (val) {
	if(isNaN($scope.Amount)){
		alert("given input is not a number");
		return;
	}
        $scope.Amount = Number($scope.Amount).toFixed(2);
    }
}]);
</script>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.