1

I have input box accepting decimal numbers with having decimal points limit upto 2 places. Also I am not allowing input to enter more than two decimal places.

eg. 9999.99

But now the problem is when I am copy some number i.e. 999999.9999 and paste it into input box I want result i.e. 999999.99

Meaning I want to truncate rest of the decimal places and don't want rounding as well.

How can I achieve this using angularjs?

Nilay Mistry
  • 76
  • 1
  • 8

2 Answers2

0

You can use ngPattern directive.

<input type="text" ng-pattern="/^[0-9]+(?:\.[0-9][0-9])?$/">

This regex would enforce exactly two places (no more or less). Just change the regex to get whichever desired behavior you want.

Araymer
  • 1,315
  • 1
  • 10
  • 16
  • my concern is numbers are not gets formatted when I am pasting it into input box – Nilay Mistry Jul 06 '17 at 03:39
  • ngPattern will just give you a truthy value of whether the text currently in the box fits the regex. You can handle that however you like. See: https://docs.angularjs.org/api/ng/directive/ngPattern – Araymer Jul 06 '17 at 03:44
0

You can accomplish this using ng-model along with $formatters and $parsers.

See more explanation here:

ngModel Formatters and Parsers

This is a TypeScript adaptation from some code I use to force currency formats.

app.directive('myModelFormat', ['$filter', function myModelFormatDirective($filter:ng.IFilterService):ng.IDirective {

    return {
        require: '?ngModel',
        link: myModelFormatLink
    };

    function myModelFormatLink(scope:ng.IScope, elem:ng.IAugmentedJQuery, attrs:ng.IAttributes, ctrl:ng.INgModelController) {

        if (!ctrl) {
            return;
        }

        const decimalWithOneDigit:RegExp = new RegExp('\\' + STRINGS.decimalSym + '\\d$');

        ctrl.$formatters.unshift(function myModelFormatFormatter(ignore:any):string {
            return $filter(attrs['myModelFormat'])(ctrl.$modelValue)
        });

        ctrl.$parsers.unshift(function myModelFormatParser(viewValue:string):any {
            const plainNumber:number = parseFloat(viewValue);
            let formatted:string = $filter(attrs['myModelFormat'])(plainNumber);

            // special case where they typed the decimal symbol but not a decimal value,
            // make sure we don't remove the symbol which prevents them from typing a decimal
            if (_s.endsWith(viewValue, STRINGS.decimalSym)) {
                formatted += STRINGS.decimalSym;
            }

            // alternate special case, they typed one decimal number, don't force it to zero, at least not yet..
            if (decimalWithOneDigit.test(viewValue)) {
                formatted = formatted.substr(0, formatted.length - 1);
            }

            elem.val(formatted);
            return plainNumber;
        });
    }
}]);
Samuel Neff
  • 73,278
  • 17
  • 138
  • 182