Get only 2 decimals

2

I have the following js:

var array = ["paco", "185.6687", "lucas", "1365.2541"]

<div ng-repeat="val in array">
   {{val}}
</div>

I know that if it were a number that makes {{val | number:2}} function but if I have that array, how do I make those cases only show me 2 decimal places?

    
asked by sirdaiz 09.06.2017 в 09:58
source

2 answers

1

In Angular you can create a formatting function, and then instead of directly outputting the variable, output the formatting function (passing the variable as an input parameter).

In your particular case, you want a function that if the input is a string, leave it as such, but if it is a number, just leave two decimal places. This could be done with a simple function:

function formateaValor(valor) {
  // si no es un número devuelve el valor, o lo convierte a número con 2 decimales
  return isNaN(valor) ? valor : parseFloat(valor).toFixed(2);
}

That you can integrate in AngularJS as follows:

var app = angular.module("miApp", []);
app.controller("miCtrl", function($scope) {
  $scope.array = ["paco", "185.6687", "lucas", "1365.2541"];
  $scope.miFormato = function(valor) {
    return isNaN(valor) ? valor : parseFloat(valor).toFixed(2);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="miApp" ng-controller="miCtrl">
  <div ng-repeat="val in array">
    {{ miFormato(val) }}
  </div>
</body>
    
answered by 09.06.2017 / 14:45
source
0
var n1 = array[1].toFixed(2);
var n2 = array[3].toFixed(2);

So you will only get 2 decimals.

for(int i = 0;i < array[].length;i++){
 if(array[i].isNaN(array[i])) {
    array[i] = array[i].toFixed(2);
  }else{

 }
}

Something like that sounds like it can work for you

    
answered by 09.06.2017 в 10:04