Problem with Decimal Math calculations in AngularJS and JavaScript

I am experiencing an issue with JavaScript calculations. On inspecting the fiddle, I noticed that the answer is displaying as rounded with no decimals, which is confusing to me.

How can I modify my code to display 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>

Answer №1

Instead of using parseInt(), which removes decimals, consider using parseFloat() if you want to ensure input values are numbers. Your scope variables are already numbers, so parseInt() doesn't add any value.

In HTML5, you can implement early input validation by using <input type="number">. This prevents users from entering non-numeric values, providing an initial layer of validation. However, allowing invalid inputs might be beneficial as it allows for intelligent error handling using JavaScript to notify users about incorrect input.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing Website Visibility: Utilizing PHP and JQuery to Update Page Content for Viewers

Imagine having a social networking platform where users can post updates and see them appear in real-time on their timeline. The challenge arises when these updates are only visible to the user currently logged in on a specific device. How can we utilize j ...

Joi mistakenly demanding certain fields that should not be mandatory

I've encountered an issue with posts validation using @hapi/joi 17.1.1. In my schema, I have two fields: textfield and picture. Although both fields are not required, the validation is still indicating that the picture field is mandatory. posts valid ...

Adjust the transparency and add animation effects using React JS

When working on a React project, I encountered an issue where a square would appear under a paragraph when hovered over and disappear when no longer hovered. However, the transition was too abrupt for my liking, so I decided to implement a smoother change ...

Guide on incorporating database-sourced audio playback using buttons in PHP and HTML

Building my website with an audio player inside has been a bit challenging. I encountered an issue when trying to combine songs loaded from the database with a play button. My goal is to have the play button change when clicked and load the song from the d ...

The concept of setTimeout and how it affects binding in JavaScript

I have limited experience with jquery, mainly using it for toggling classes. However, I will do my best to explain my issue clearly. I have three div elements and when one is clicked, the other two should rotate 90 degrees and then collapse to a height of ...

Socket.io operates individually with each user

Showing a basic web-chat using socket.io. Node.js code: io.on('connection', function(socket) { // Sends 'hello world' message to all users socket.emit('send:message', { text: 'hello world' }); ...

Iterate through the list retrieved from the backend

I have a list coming from the backend that I need to iterate through and hide a button if any element in the list does not have a status of 6. feedback The response returned can vary in length, not always just one item like this example with 7 elements. ...

Avoid running another process before the current one finishes in jQuery

I have a situation where I am using $.ajax inside a for loop in jQuery. for(var i=0; i < 2; i++) { $.ajax({ url :"/models/getdata"+i, dataType:"json", success:function(data) { } }); } The issue is that before the success function for i=0 completes, ...

I need to know how to create a patch request in Vue.js and simultaneously modify the marks input for specific individuals by using v-model

Hello there, I am currently developing a student assessment input form using vuejs, express, and mongoDB. The backend API is complete and functioning properly when tested with postman. Here is the code: // UPDATE MARKS router.patch('/:studentId' ...

How can I retrieve text that is enclosed within 2 specific tags and then format the output according to my preference?

Is it possible to extract text between specific tags and format the output as desired? Are there any tools or scripts available for this task? For instance: [b]1.[/b] [artist]Norman Bass[/artist] – How U Like Bass? (Warp Brothers Club Mix) [i](3:26 ...

Can Regex expressions be utilized within the nodeJS aws sdk?

Running this AWS CLI command allows me to retrieve the correct images created within the past 45 days. aws ec2 describe-images --region us-east-1 --owners self -- query'Images[CreationDate<`2021-12-18`] | sort_by(@, &CreationDate)[].Name&apos ...

Storing personalized HTML content in a database for individual users: A step-by-step guide

I have a JavaScript code snippet similar to this fiddle: http://jsfiddle.net/nj4N4/7/ On my webpage, it displays like this: image. When you click on the "add a year" button, a table resembling year2 appears above the previous year. Now, I'm looking ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

retrieve the source code from all .js links found within the document

There is a file labeled urls.txt. https://website.tld/static/main_01.js https://website.tld/static/main_02.js https://website.tld/static/main_03.js .... All the source code from every .js file in allsource.txt needs to be extracted. Instructions: To ge ...

Guide on subscribing to an object from a service in Angular 2/5

I am facing an issue where I need to update my property component with data received from the server. In the Service, I have implemented something like this: private events: Event[] = []; eventChanged = new Subject<any>(); // Edit: added an observa ...

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

Having trouble retrieving a value from the $http promise, causing the code within the then() function to not run as expected

In the past, I encountered a challenge with the $http service which I managed to solve by creating a dedicated service for handling my requests. However, as my requests grew larger, this solution started to seem inefficient. Instead of just assigning a sim ...

ng2-idle server side rendering problem - Uncaught ReferenceError: document is undefined

Can ng2-idle be used for idle timeout/keepalive with pre-rendering in Angular 4? I followed this link for implementation: It works fine without server pre-rendering, but when I add rendering back to my index.html, I keep getting the following error: Exce ...

The module "angular2-multiselect-dropdown" is experiencing a metadata version mismatch error

Recently, I updated the node module angular2-multiselect-dropdown from version v3.2.1 to v4.0.0. However, when running the angular build command, I encountered an "ERROR in Metadata version mismatch for module". Just to provide some context, I am using yar ...

Utilizing an npm Package in Laravel - Dealing with ReferenceError

I'm having trouble with the installation and usage of a JS package through npm. The package can be found at . First, I executed the npm command: npm install --save zenorocha/clipboardjs Next, I added the following line to my app.js file: require(& ...