Sum values with Angularjs

Asked

Viewed 514 times

0

I am trying to add two values. Example value 150.00 and value 50.00. I tried to do so {{value + value}} and is returning 150.0050. No way to do the sum this way? ng-repeat value and input field value

2 answers

0

This is because valueB and valueB are not numbers but strings, so by summing it is actually concatenating its values.

I’d have to wear something like {{Number(valorA) + Number(valorB)}}

Or convert the model directly into the controller, like this: $scope.valorA = parseFloat(valorA);

Just watch out for the number format, which should always have point as decimal separator, and never comma.

0

It’s very quiet to do what you need. In Javascript to work with float values is nice you convert the value. Note: The values must be using the . and not a , the ideal would be that its value is already with a semicolon instead of a comma, for example: 150.00 but if it is a comma string ex: '150.00' you can use a replace with a parseFloat. I’ll put a simple example to try to help.

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

app.controller('moduloArray', function($scope) {
    $scope.dadosArray = [{
        valor1: '138,00',
        valor2: '25,00'
    }, {
        valor1: '56,00',
        valor2: '84,00'
    }, {
        valor1: '16,00',
        valor2: '73,00'
    }];
    
    //faz o replace trocando vírgula por ponto, convertendo em float e somando os dois numeros
    $scope.calcularValor = function(v1, v2){
      return parseFloat(v1.replace(',','.'))+parseFloat(v2.replace(',','.'));
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="meuapp">
    <div ng-controller="moduloArray">
        <table>
            <tr ng-repeat="d in dadosArray">
                <td>
                    <span ng-bind="d.valor1"></span> +
                    <span ng-bind="d.valor2"></span> =
                </td>
                <td>
                    <b ng-bind="calcularValor(d.valor1, d.valor2)"></b>
                </td>
            </tr>
        </table>
    </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.