how to display trailing zeros in input type number (angular, js)

I have to display in UI on input tag, even whole numbers like 15 as 15.00 (or as many decimals user decides upon).
I’m currently using an input of type number with attributes min and max.

So far, the only options which I have seen online are to use input type text. (trying not to as it doesn’t make sense to switch to text, as I’m only working with numbers).

I have tried using step attribute but doesn’t cover the case for trailing zeros (neither chrome or firefox will show trailing zeros for a number).

Any help will be greatly appreciated.

If decimals set as 4, the following needs to happen: ex.
15.2 shown as 15.2000
100 shown as 100.0000

Answer

To achieve expected result, use below of using ng-blur with parseFloat and toFixed

Option 1:

Use ng-blur option to format entered number by parseFloat with toFixed(4)

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $filter) {
  $scope.format = function(event, $filter) {
    const val = event.target.value;
    const decimalCnt = val.split('.')[1] ? val.split('.')[1].length : 0;
    event.target.value = decimalCnt && decimalCnt > 4 ? event.target.value : parseFloat(val).toFixed(4)
  }
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">
    <input type="text" ng-model="test" ng-blur="format($event)"><br>
  </div>

</body>

</html>

codepen – https://codepen.io/nagasai/pen/xxxGoNK

Option 2:
Create attribute directive for displaying entered value with decimal values

var app = angular.module('myApp', []);

app.controller("myCtrl", function($scope, $filter) {});

app.directive("decimalValues", function($filter) {
  return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, element, attr, ngModel) {
      element.on('blur', function(e) {
        let val = element.val();
        const decimalCnt = val.split('.')[1] ? val.split('.')[1].length : 0;
        val = decimalCnt && decimalCnt > 4 ? val : parseFloat(val).toFixed(4)
        element.val(val)
      })
    }
  };
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">

    <input type="text" ng-model="test" decimal-values><br>

    <br>

  </div>

</body>

</html>

codepen – https://codepen.io/nagasai/pen/NWWqZQY

Leave a Reply

Your email address will not be published. Required fields are marked *