0

I'm having an issue when doing calculation with javascript. As you can see in the fiddle, the answer show up rounded with no decimals and I dont understand why.

What do I need to do to show the decimals of $scope.total?

var moment = angular.module('moment',[]);
moment.controller('momentCtrl', ['$scope', function($scope) {
  
  
  $scope.val1 = 96;
  
  $scope.val2 = 18;
  
  $scope.val3 = Math.PI;
  
  $scope.val4 = 13.5;
  

 $scope.total = parseInt( $scope.val1 ) + parseInt( $scope.val2 ) - parseInt( $scope.val3 ) - parseInt( $scope.val4 );
  
  
 
  
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="moment" ng-controller="momentCtrl">
Value = {{total}} <br>
Should be something like 97.3584
  </div>

3
  • You are using parseInt... Commented Mar 14, 2016 at 14:51
  • Why are you using parseInt anyway? Commented Mar 14, 2016 at 14:51
  • It's not clear why you are using parseInt in your calculations. Those are all numbers. Commented Mar 14, 2016 at 14:52

1 Answer 1

2

You're using parseInt() which removes the decimals, and since your scope variables are all already numbers, it doesn't actually contribute anything. If you're trying to make sure that the inputs are numbers, you can use parseFloat().

For early input assurance in HTML5, you can use <input type="number">. It stops a user from even attempting to put in a non-number, which is a good early catch (though you might want to allow invalid inputs, since you can then use JS to intelligently decide how to notify the user about what's wrong).

Sign up to request clarification or add additional context in comments.

2 Comments

@ryanyuyu Great suggestion
Since you've integrated my comment into your answer (rather well I must say), I'm removing the now obsolete comment. I've also made a few cosmetic fixes to your answer. I'll delete this comment too in a few minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.