Create a separate function to split up the numbers provided in the prompt

I've developed a program that calculates the denomination of bank notes (2, 5, 10, 20, etc.) you need to pay based on a number you input in the prompt.

Now, I'm looking to enhance this program by taking the input number from the first step and dividing it by a new number entered by the user in a prompt. This will help me calculate the average cost of one item.

Can someone guide me on how to achieve this?

Below is the code I've written for the initial part.

var amount = prompt("Enter amount:");

var bankNotes = [500, 200, 100, 50, 20, 10, 5, 2, 1];
var totalNotes = 0;
var output = "";
for (i = 0; i < bankNotes.length; i++) {
  var x = amount / bankNotes[i];
  if (x >= 1) {
    var difference = Math.floor(x) * bankNotes[i];
    amount = amount - difference;
    totalNotes = Math.floor(x) + totalNotes;
    output = output + Math.floor(x) + "x" + bankNotes[i] + ",";
    console.log(output);
  }
}
window.onload = function() {
  document.getElementById("display").innerHTML = "Payment requires " + output;
}
<span id="display"></span>

Answer №1

It seems there might be some uncertainty in interpreting the question, but if you simply want to include another user-input variable and perform a division operation with it in your program, you can achieve it with the following code snippet (although the practical application of this is unclear):

var number = prompt("Enter a number:");
var divisor = prompt("Divide by this number:");

var banknote = [500, 200, 100, 50, 20, 10, 5, 2, 1];
var count = 0;
var result = number / divisor;
var output = "";
for (i = 0; i < banknote.length; i++) {
  var x = number / banknote[i];
  if (x >= 1) {
    var difference = Math.floor(x) * banknote[i];
    number = number - difference;
    count = Math.floor(x) + count;
    output = output + Math.floor(x) + "x" + banknote[i] + ",";
    console.log(output);
  }
}
window.onload = function() {
  document.getElementById("go").innerHTML = "Payment requires " + output + " whereas the result of the division is: " + result;
}
<span id="go"></span>

In essence, all you need to do is introduce another prompt, store its value in a new variable, and then carry out a division operation with it.

Best regards, C

Answer №2

To maintain certain local state, experiment with the following:

Codepen

  <span id="gremo"></span>
  <span id="avg"></span>
  <button id="add">add item</button>
var pastItemPrices = [];

function calculateBills() {
    var amount = prompt("Enter amount:");
    pastItemPrices.push(parseInt(amount));
    var banknote = [500, 200, 100, 50, 20, 10, 5, 2, 1];
    var number_of_banknotes = 0;
    var display = "";
    for (i = 0; i < banknote.length; i++) {
        var x = amount / banknote[i]; 
        if (x >= 1) {
            var difference = Math.floor(x) * banknote[i];
            amount = amount - difference;
            number_of_banknotes = Math.floor(x) + number_of_banknotes;
            display = display + Math.floor(x) + "x" + banknote[i] + ",";
        }
    }
    document.getElementById("gremo").innerHTML = "To pay, you will need " + display;
    document.getElementById("avg").innerHTML = "Average price: " + pastItemPrices.reduce((total, price) => total + price) / pastItemPrices.length
}

window.onload = function() {
    document.getElementById("add").addEventListener("click", calculateBills);
    calculateBills();
}

Answer №3

Is this the type of code snippet you were looking for?

function calculateAmount() {
  var amount = prompt("Enter the amount:");
  const copyAmount = amount; // take a copy
  var banknotes = [500, 200, 100, 50, 20, 10, 5, 2, 1];
  var numBanknotes = 0;
  var display = "";
  for (i = 0; i < banknotes.length; i++) {
    var x = amount / banknotes[i];
    if (x >= 1) {
      var difference = Math.floor(x) * banknotes[i];
      amount = amount - difference;
      numBanknotes = Math.floor(x) + numBanknotes;
      display = display + Math.floor(x) + "x" + banknotes[i] + ",";
//      console.log(display);
    }
  }
  document.getElementById("output").innerHTML = "The payment requires " + display;
  setTimeout(function() { secondAmount(copyAmount) } ,10); // allow DOM update
}
function secondAmount(copyAmount) {
  var newAmount =  prompt("Enter another amount")
  if (copyAmount && isNaN(copyAmount) || isNaN(newAmount)) {
    document.getElementById("output").innerHTML = "Unfortunately, not numbers";
    return;
  }
  else {
    console.log(copyAmount, newAmount, copyAmount / newAmount)
    document.getElementById("output").innerHTML += "<br/>" + (copyAmount / newAmount).toFixed(2)
  }
}  
window.addEventListener("load", calculateAmount)
<span id="output"></span>

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

What advantages come from caching the document object for improved performance?

Usually, I cache DOM objects used in a script. However, recently I found myself having to reference the document object within a jQuery wrapper. I started questioning whether caching $(document) is necessary since there's only one document object per ...

Tips for applying stroke and shadow effects specifically when the mouse is moving over a canvas:

How can we create a shadow and stroke effect for circles drawn using HTML canvas only during mouse hover? I have two circles and would like to add a shadow and stroke effect when the mouse hovers over them. However, the issue is that once the mouse moves ...

Using MongoMapper with Rails to efficiently render arrays in views

In my Rails application, I have a controller that retrieves data from MongoDB. The specific field I need is actually an array, and I want to display it in an erb view. Currently, my workaround involves setting the JavaScript variable directly in the view ...

Angular JS Integration with PapaParse

Currently enjoying the efficiency of PapaParse's CSV parsing and unparsing features. Interested in integrating this with Angular JS - anyone able to assist with this integration? Excited about incorporating PapaParse into an Angular environment. Work ...

I am excited to create a Dynamic Routing system that selects specific elements from an array of objects using Typescript

1. crops-list.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-crops-list', templateUrl: './crops-list.component.html' ...

What sets TypeScript apart from AtScript?

From what I understand, TypeScript was created by Microsoft and is used to dynamically generate JavaScript. I'm curious about the distinctions between TypeScript and AtScript. Which one would be more beneficial for a JavaScript developer to learn? ...

Setting up Geolocation

I have been utilizing an APM tool for my work. The tool currently requires a pop-up in order to capture the user's location. However, there is now a need to capture the user's location without the pop-up appearing. Is there a method or workaroun ...

Finding your way through Bootstrap Datepicker using the Previous and Next Buttons

Is there a way to implement Previous and Next Button functionality for navigating a Bootstrap Datepicker using jQuery, similar to the illustration below? https://i.sstatic.net/e9I7P.png I attempted the following approach: function PrevNext(isnextbtn) ...

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

Arranging divs using inline-block display. How to adjust the heights consecutively?

After much searching and attempting, I am still unable to achieve a simple task. My goal is to apply display inline-block to some divs while aligning them in a row, similar to the image below: https://i.sstatic.net/iLhLS.png The issue arises when number ...

Although AJAX $.post functions properly in the View, it seems to encounter issues when relocated to a separate .js file. Interestingly, all other JQuery functions work

I have recently delved into MVC, JQuery, and AJAX, and encountered a perplexing issue. After completing the initial development of a practice website, I dedicated time to enhance the interactivity using JQuery. Everything was functioning smoothly until I ...

Establishing a universal function within Ionic AngularJS

I have the following code snippet, where I have added a reset function that I want to be able to use from ng-click in any part of any template. angular.module('starter', ['ionic', 'starter.controllers', 'starter.services ...

The if-else statement doesn't seem to be functioning correctly once the else condition is included

I'm currently developing a search function for an address book that iterates through the contact array and displays them in a popup. Initially, it was working correctly by finding and displaying the contacts that were found. However, once I added the ...

What is the significance of the statement "What is the meaning of "#include <common>" in Three.js, WebGL, and GLSL?

The Three.js shader example linked here uses a function called rand() with a vec2 input to create random numbers. Interestingly, the function is not defined within the shader code itself. Instead, it appears to be included through the use of #include < ...

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

The AreaChart in Google is displaying incorrect dates on the axis

I have encountered an issue that I am struggling to resolve. I am in the process of creating a Google Area Chart using a JSON response from a server, specifically with date type columns. Below is the JSON data obtained from the server (copy/paste), organi ...

Why is `screen` important?

Recent articles in June 2020 discussing "how to utilize react testing library" often showcase a setup similar to the one below: import React from 'react'; import { render, screen } from '@testing-library/react'; import App from '. ...

Discover the two words before and after a span element using jQuery

data-color="red"I am looking for 2 words before and after the span tags. Here is the html code: <p>This pathway has an inner and an outer wall. The pressure <span data-color="red" class="highlight">inside the</span> eye closes the tun ...

Top methods for handling special characters in a database

My mysql database is filled with json data that is then used in angularjs for display purposes. Some of the text within the database includes escaped quotes and double quotes, for example: Do you possess at least a bachelor\'s degree in child ...

What steps are needed to set up my Express server so that it can render all my content, rather than just my HTML file?

I need help setting up a server for my project using Express. Here is the structure of my file directory: root-directory ├── public │ ├── css │ │ └── styles.css │ ├── images │ │ └── img1.png | | └ ...