0

In following expression

parseFloat((($scope.Product.cost/100) * $scope.Product.profit) + $scope.Product.cost);

+ operator is concatinating the values and i expect it to perform addition.

irfan shafi
  • 524
  • 1
  • 6
  • 21

2 Answers2

2

...even after parseFloat method

The + part of that expression isn't after the parseFloat, it's before the parseFloat.

You probably wanted:

(($scope.Product.cost/100) * $scope.Product.profit) + parseFloat($scope.Product.cost);

Note that cost in the above is implicitly converted to number when you use it in the /100 expression, but you're explicitly converting it with parseFloat elsewhere. Those two things don't do quite the same thing.

I'd probably prefer to convert, then calculate:

var cost = parseFloat($scope.Product.cost); // or +$scope.Product.cost
var profit = parseFloat($scope.Product.profit); // or +$scope.Product.profit
var result = ((cost/100) * profit) + cost;

See this answer for a rundown of the differences between implicit string-to-number conversion vs. parseFloat (and others).


Side note: You don't need some of the parens you're using, the last line of the convert-then-calculate above could be:

var result = (cost/100) * profit + cost;

...because * has higher precedence than +. But the extra () are harmless.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

Convert each of the variables in your expression to number by applying the + unitary operator on each of them:

+$scope.Product.cost/100 * +$scope.Product.profit + +$scope.Product.cost;

As noted in comments, the coercion to float is implied for the first part of the expression by the / and * operators, but not so for the + operator, which will coerce the first numerical result to string unless the second argument is first converted to number as well.

So the first two + unitary operators are not really necessary.

trincot
  • 317,000
  • 35
  • 244
  • 286