JavaScript errors due to miscalculations Incorrect calculations lead

Here is the formula I am using in my Javascript code:

total = parseFloat(unit * rate) + 
        parseFloat(rateamount) + 
        parseFloat(((unit * rate) + 
        (rateamount)) * (tax/100));

The values for the variables are as follows:

unit = 5, rate = 10, rateamount = 10, tax = 10.

Currently, the formula is returning a result of 561, which is incorrect.

If you have any suggestions or solutions, please feel free to share them. Thank you!

Answer №1

The issue lies in the concatenation of strings within this portion of your code:

parseFloat(((unit * rate) + (rateamount))

You neglected to parse rateamount, which is represented as a string '10'.

The corrected version should look like this:

var unit = '5',
  rate = '10',
  rateamount = '10',
  tax = '10';

var total = parseFloat(unit * rate) + parseFloat(rateamount) + parseFloat(((unit * rate) + parseFloat(rateamount)) * (tax / 100));
console.log(total);

However, it's advisable not to utilize parseFloat multiple times; instead, it's better to parse the values just once before proceeding with any calculations to prevent errors.

var unit = '5',
  rate = '10',
  rateamount = '10',
  tax = '10'

var parsedUnit = parseFloat(unit),
  parseRate = parseFloat(rate),
  parsedRateamount = parseFloat(rateamount),
  parsedTax = parseFloat(tax);

var total = parsedUnit * parseRate + parsedRateamount + ((parsedUnit * parseRate) + (parsedRateamount)) * (parsedTax / 100);
console.log(total);

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

Every other attempt at an Ajax request seems to be successful

I'm new to using ajax and I'm having an issue with submitting a form through a post request. Strangely, the code I wrote only works every other time. The first time I submit the form, it goes through ajax successfully. However, on the second subm ...

The switch statement is not yielding any results

I am currently working on a test that involves processing a string through a switch statement. However, I am facing an issue where the integer value set in the case of the switch statement is not being passed correctly. As a result, the subsequent if state ...

Sticky header/navigation bar implementation in React Native for consistent navigation across views

Currently, I am working on creating a consistent navbar/header for my React Native app. At the moment, when I switch between views in my code, the entire interface changes. It functions properly, but the navbar/header scrolls along with the view, making i ...

Upon initiating npm start in my React application, an error was encountered: internal/modules/cjs/loader.js:834

Upon downloading my React course project, I proceeded to install dependencies and run npm start. To my dismay, I encountered the following error: PS C:\Users\Marcin & Joanna\Desktop\react-frontend-01-starting-setup> npm start &g ...

Struggling to make a form submit work with AngularJS and a Bootstrap datetime picker

Struggling to create a post and include name and datetime using a bootstrap datetimepicker. After selecting the datetime and clicking add, nothing happens. However, if I manually type in the field and click add, it submits successfully. Despite reading up ...

Error in Redux app: Attempting to access the 'filter' property of an undefined value

I am currently encountering an issue with my reducer: https://i.stack.imgur.com/7xiHJ.jpg Regarding the props actual, this represents the time of airplane departure or arrival, and it is a property within my API. The API structure looks like this: {"body ...

PHP jQuery buttons for popovers

With a simple click of a button, I can generate 8 presentations and then edit each one individually by clicking on its respective name. Within this editing process, there is another form where I would like to include additional buttons that allow me to cus ...

When attempting to install material UI in my terminal, I encounter issues and encounter errors along the way

$ npm install @material-ui/core npm version : 6.14.4 Error: Source text contains an unrecognized token. At line:1 char:15 $ npm install <<<< @material-ui/core CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

Is it possible to vertically center a child div within its parent container using JavaScript when the page loads without explicitly setting its position?

Using JavaScript to vertically center a child div within a fluid container involves calculating the height of both elements and positioning the child div accordingly. However, one issue faced is that the position is not set when the page loads. To solve ...

The condition is not being recognized after clicking the third button

When the button is clicked for the first time in the code snippet below, all divs except for the red one should fade out. With each subsequent click, the opacity of the next div with a higher stack order should be set to 1. Everything works fine until the ...

Steps to close a socket upon session expiration

I am currently working on a small express application that also incorporates a socket program. Everything works perfectly when a user successfully logs in - it creates the session and socket connection seamlessly. However, I encountered an issue where eve ...

Cloning jQuery with varied PHP array value

So, I have the given PHP values: PHP: <?php $names = array("Mike","Sean","Steve"); ?> <script type="text/javascript"> var name_data = <?php echo json_encode($names); ?>; </script> <div class="container"> <div cl ...

Modifying td background color according to values in a PHP array

Trying to update the background color of a td element with the code below. However, it seems that the code needs some adjustment as the color is not being applied. Any assistance or alternative solutions would be greatly appreciated. Snippet of PHP code: ...

What is the best approach to perform a search in mongoose based on specific query parameters?

I have a form that allows users to search for transactions by specifying the buyer name, item name, or both. This means I can receive any of these queries: localhost:8000/allPayments/?i=pasta localhost:8000/allPayments/?b=Youssef localhost:8000/ ...

What is causing the width discrepancy in my header section on mobile devices?

Help needed with website responsiveness issue! The site works fine on most screen sizes, but when it reaches around 414px in width, the intro section becomes too wide for the screen. Any ideas on what could be causing this problem? html: <nav id="m ...

Adjusting the dimensions of the canvas leads to a loss of sharpness

When I click to change the size of the graph for a better view of my data in the PDF, the canvas element becomes blurry and fuzzy. Even though I am using $('canvas').css("width","811"); to resize the canvas, it still results in a blurry graph. I ...

Transitioning from Jquery to vanilla JavaScript or transforming Jquery code into pseudo code

Struggling with a snippet of jQuery code here. While I have a good grasp on JavaScript, my knowledge of jQuery is somewhat limited. I am seeking assistance to analyze the following code in order to translate it into plain JavaScript or pseudo code that ca ...

What is the best way to convert an array of data into a dataset format in React Native?

Within my specific use case, I am seeking to reform the array structure prior to loading it into a line chart. In this context, the props received are as follows: const data = [26.727, 26.952, 12.132, 25.933, 12.151, 28.492, 12.134, 26.191] The objective ...

While iterating through a dynamically generated JSON data array, omitting the display of the ID (both title and value) is preferred

I am working with a JSON data Object and using $.each to dynamically retrieve the data. However, I want to display all values except for one which is the ID. How can I achieve this and prevent the ID from being displayed in the HTML structure? Thank you. ...