JSFiddle - React, Tailwind, and code Playground

by Prajeesh_PR

HTML

<div ng-app="formatter">
   <div ng-controller="so">
        <input ng-model="salary"></input>
        <div>{{salary}}</div>
   </div>
</div>

JavaScript

var app = angular.module('formatter', []);
app.controller('so', function($scope) {
	$scope.$watch('salary', function(){
		// strip out all the commas and dots
		var temp = $scope.salary;
		if (!temp) return; // ignore empty input box
		var lastChar = temp[temp.length-1];
		if (lastChar === ',' || lastChar === '.') // skip it/allow commas
			return;
		var a = temp.replace(/,/g,'');  //remove all commas
		//console.log(a);
		if (isNaN(a)) 
			$scope.salary = temp.substring(0, temp.length-1); // last char was not right
		else {
			var n = parseInt(a, 10); // the integer part
			var f = ''; // decimal part
			if (a.indexOf('.') >= 0) // decimal present
				f = ('' + parseFloat(a)).substr(a.indexOf('.'));
			console.log('float: '+f);
			var formatted_salary = '';
			var count = 0;
			var ns = '' + n; // string of integer part
			for (var i=ns.length-1; i>=0; i--) {
				if (count%3===0 && count>0)
					formatted_salary = ',' + formatted_salary;
				formatted_salary = ns[i] + formatted_salary;
				count += 1;
			}
			formatted_salary = formatted_salary + (f ? f : '');
			console.log(formatted_salary);
			$scope.salary = formatted_salary;

		}
	})
})