What causes the variable "change" to display unexpected results?

Why isn't the function working as expected? I need the change to be 0. I believe there must be a more efficient way to solve this issue, but what's bothering me is that the "change" variable is giving strange values...need help!

 function checkCashRegister(price, cash, cid) {
      var change= cash-price
      var money={
        'PENNY':0.01,
        'NICKEL':0.05,
        'DIME':0.1,
        'QUARTER':0.25,
        'ONE':1,
        'FIVE':5,
        'TEN':10,
        'TWENTY':20,
        'ONE HUNDRED':100}
        console.log(change,'start')
        let i=8;
      while(change>0){
    
    // console.log(cid[i][1])
      if(change<cid[i][1]&&change>money[cid[i][0]]){
        console.log(cid[i][0], 'cid')  
        console.log(money[cid[i][0]],'money')
        change=change-money[cid[i][0]] 
        console.log(change, 'change') 
        i=8;    
  }  
  i--
  }
  
}

checkCashRegister(19.4, 20,
[["PENNY", 1.01], 
["NICKEL", 2.05], 
["DIME", 3.1], 
["QUARTER", 4.25], 
["ONE", 90], 
["FIVE", 55], 
["TEN", 20], 
["TWENTY", 60], 
["ONE HUNDRED", 100]]);

Answer №1

When saving a float value in JavaScript as binary data, numbers like 19.4 may not be exactly represented as 19.4. This is why calculations such as 20 - 19.4 may not result in exactly 0.6.

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

Guidelines on utilizing the information collected from social signups to seamlessly guide users towards finishing the registration process in [passport, node.js]

As a newcomer to the realm of node.js for a few months, I am still grappling with some concepts. Specifically, I need guidance on redirecting users to complete their registration using data acquired from social signups such as Facebook or Google. Current ...

Saving JavaScript Object Notation (JSON) information from Node.js into MongoDB

Currently, I am successfully pulling weather data in JSON format from Wundground using their API. The next step for me is to store this data in MongoDB for future use. After retrieving the data and attempting to write it to a Mongo collection, I encountere ...

Despite being initialized previously in JavaScript, the attribute of the object is still showing as undefined

After using an attribute from an Object multiple times, it suddenly appears as undefined when I call it in another function. Even though I have checked its values with console.log and they seem to be assigned correctly. Can anyone help me figure out what I ...

How can I incorporate dynamic data to draw and showcase graphs on my website using PHP?

I am currently working on a project that requires displaying a graph showing the profit of users per day. Currently, I have implemented code to display a static graph on my page. <script type="text/javascript" src="https://www.google.com/jsapi">< ...

What methods can be utilized to create sound effects in presentations using CSS?

Let us begin by acknowledging that: HTML is primarily for structure CSS mainly deals with presentation JS focuses on behavior Note: The discussion of whether presentation that responds to user interaction is essentially another term for behavior is open ...

Toggle class for a div upon clicking

I am attempting to add a class to a div element when it is clicked. Unfortunately, I'm having trouble getting it to work despite setting it up in the following manner: Javascript: function choose() { this.addClass("selected"); } HTML: <div ...

Verify Ionic storage for an item

Is there a way to display an introductory slider only once for new users when they install the app? Solution If the user installs the app, set an item in the storage called intro with a value of false When the user opens the app, check the intro item. I ...

Is it possible to retrieve JavaScript object properties using HTML elements?

I have fetched an array of objects using jQuery.getJSON(). Each object should be represented by an HTML div element, allowing users to click on the element and access all properties of the corresponding object. What is the most efficient approach for achie ...

Showing text on an ajax loader

While making an ajax call, I have implemented functions that are called on success. To enhance user experience, I am displaying a spinner during the call and hiding it once completed. My goal is to show a message along with the spinner to indicate which fu ...

Tips for monitoring a field within an angularJS factory

Within my web application, I am utilizing a factory. This factory contains an object named mapLayers. Within my controller, I am assigning this factory.mapLayers object to a variable on the scope called $scope.mapLayers and using ngRepeat to iterate over i ...

Is there a way to update a state only if it matches the corresponding ID?

updateItem = (id) => { this.setState( { lanche: [ { id: id, updateItem: true }] } ) } Instead of updating all items in the array, I want to specifically target and edit the item with a m ...

Trouble with database updates in Mongodb using Node.js: issues with ".findOneAndUpdate()" operation

When attempting to update my database using .findOneAndUpdate(), I encountered an issue where the embedded document competitorAnalysisTextData remained empty despite no error messages. // on routes that end in /users/competitorAnalysisTextData // -------- ...

The page you are trying to access does not support the HTTP request method 'GET'. Please try a different method to access the page

I have been attempting to incorporate AJAX for asynchronous communication with the server. However, I keep encountering the following error message. Any insights on how to resolve this issue? org.springframework.web.servlet.PageNotFound.handleHttpReques ...

Integrating Express into a React Webpack project

I am currently in the process of integrating express into my React project to establish connections with databases for storing form data. As of now, I am using webpack to create a dev server that displays my React view. My technology stack includes... Web ...

A React component utilizing dangerouslySetInnerHTML and including CSS styles

One of my React components displays the following element: <div dangerouslySetInnerHTML={{__html: this.props.htmlString}}/> While the html renders correctly, I am facing a challenge with my client-side CSS code affecting the component I am renderin ...

How do you invoke a function from within another function in AngularJS?

I'm facing an issue with a function that needs to be called every time a page is loaded. I attempted to achieve this by using the following code: callFunction(); function callFunction(){ $scope.onClickModel(); } ...

POST data not being sent via AJAX

I am trying to use AJAX to submit form data to a PHP function, but it seems like the data is not being transmitted. Here is the code for the HTML Form: <form onSubmit="return registration();" id="registration_form"> <input type="email" id="e ...

Angular: How can objects be efficiently stored in a service for display in the view and use of CRUD functions to interact with the server?

I am exploring different options for creating a service that retrieves relational data from the server. I have two potential approaches in mind, but I am having trouble deciding between them. The first option involves returning the data as a multidimensio ...

The string that matches the duration of hour, minute, and second (HMS)

There is a need to extract the digits before h, m, and s into their own groups. The objective is to capture all three groups if possible, but if one or two groups are missing, then the last group(s) should be captured. Currently, the regex /(\d+)(?=h ...

Combining two JSON objects in JavaScript is simple when their IDs correspond to each other in both objects

I have a query related to merging two different objects from the database, both in JSON format. These two objects share two key/value pairs: IRBId = ... and id = ..., which can be seen in the examples below: OBJ 1 { "data":{ "IRBs":{ "n ...