Please find the fiddle http://jsfiddle.net/q2SgJ/5/
<div ng-app="">
<div ng-controller="Ctrl">
WANTS: {{val | number:2}} in "input" elelent<br>
2 decimal in input: <input ng-model='val'> <br>
2 decimal in input: <input type="number" step="0.01" ng-model='val'><br>
2 decimal in input: <input ng-model='val' value="{{val |number:2}}"> <br>
</div>
</div>
How can I restrict the decimal places to 2 digits in an INPUT field. As in the example {{val | number:2}}
works, but not sure how to use it to format the ng-model attached to an field. I could have formatted the data/model itself, but I have few values I like to keep the extra decimal, but only display 2 decimal.
Thanks.
To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.
Allow Only Numbers in Angular Form Input For handling only numbers in the input box we simply add an input control with the ( keypress ) event handler to call the keyPressNumbers() . Below is the code snippet for this along with the output. You clearly see that only numbers are present in the input box.
To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places.
You can write a directive to control this functionality. It is not something that ships with angular, but directives can control how things look and work on the page.
I wrote a simple one: http://jsfiddle.net/q2SgJ/8/
This is the linking function that does the trick:
link:function(scope,ele,attrs){
ele.bind('keypress',function(e){
var newVal=$(this).val()+(e.charCode!==0?String.fromCharCode(e.charCode):'');
if($(this).val().search(/(.*)\.[0-9][0-9]/)===0 && newVal.length>$(this).val().length){
e.preventDefault();
}
});
}
This works at limiting the input to 2 decimal places, but doesn't format the input to two decimal places. Anyways, it is a starting point. I am sure you can look up other examples and write your own directive to handle this the way you want. The thing about Angular is that it is not a framework with an answer to every question, but a framework that allows you to create additional functionality than what HTML5 provides alone and makes it very simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With