kl02
kl02

Reputation: 582

angularjs losing decimal & negative vals ignored

I've got a short form where the values need to be totaled so I can do math with them. For whatever reason, values set via input-radio turn the numbers into strings, and the only way I can find for angularjs to get numbers to stay numbers is using math.round or math.floor. Both of these convert fractions to whole numbers, so I end up with wacky things like .5, 1, and .5 being equal to 1, instead of two. Even if I finagle things to do whole numbers, I'm also trying to do negative numbers, and those just seem to be skipped.

Here's the specific part that's giving me fits. I've got the vars spelled out so I can output them in the html, but the final version would use the line that's commented out.

$scope.updateValue = function () {
  var one = $window.Math.floor($scope.one);
  var two = $window.Math.floor($scope.two);
  var three = $window.Math.floor($scope.three);      
  $scope.perperson = (one + two + three); 
//$scope.perperson =  $window.Math.floor($scope.one + $scope.two + $scope.three);  
  $scope.population = $window.Math.floor($scope.perperson * $scope.total);

};

Here's the plnkr. How can I get the numbers to stay as fractions, and to subtract negative numbers instead of ignore them?

Upvotes: 2

Views: 540

Answers (1)

Ben Lesh
Ben Lesh

Reputation: 108481

This isn't an Angular issue so much as it's a JavaScript issue.

To convert a string to a number in JavaScript you can use:

parseFloat('1.4'); //1.4
parseInt('1.4'); //1
+'1.4'; //1.4  (+ works like shorthand for parseFloat)

Outside of that, as far as Angular is concerned, whatever you put in value="1234" is a string. .. because it's a string. ;)

Here's an updated plunker

http://plnkr.co/edit/XRcAqML0jYm5IqIiaXSX?p=preview

Upvotes: 2

Related Questions