Application that calculates price depending on quantity in JavaScript - javascript

I have this exercise that I am struggling to comprehend the logic to achieve the outcome when qty is more than 3:
An application to calculate the price of pizzas (listed below) that will be purchased during a promotional period. The number of pizzas will be entered by the user.
One large pizza will cost $6.45.
Two large pizzas will cost $12.00.
Three large pizzas will cost $14.00.
Four or more pizzas will use a combination of the above prices to ensure the best price for the customer. For example, the best price for five pizzas would be two pizzas ($12.00) + three pizzas ($14.00).
The algorithm must also take account of all possible situations by using sequence, selection and iteration structures.
Below is my code so far:
let calcOrder = () => {
// get inputs
var qty = document.getElementById("quantity").value;
var price = 6.45;
var price2 = 12.0;
var price3 = 14.0;
var totalPrice;
// validate missing, non-digit, negative inputs
if (qty == "") {
document.getElementById("message").innerHTML = "Missing input";
} else if (isNaN(qty)) {
document.getElementById("message").innerHTML = "Numbers only";
} else if (qty < 0) {
document.getElementById("message").innerHTML =
"Negative numbers are not allowed";
} else {
//calc total
if (qty == 1)
{
totalPrice = price;
}
else if (qty == 2)
{
totalPrice = price2;
}
else if (qty == 3)
{
totalPrice = price3;
}
//output total
document.getElementById("message").innerHTML =
`Total price is $${totalPrice}`;
}
// prevent form from submission
return false;
};
Thank you

you can use division and mod operation to calculate the price:
(this example assuming all check you did valid input are already done)
const qte = document.getElementById("quantity").value;
const price = 6.45;
const price2 = 12.0;
const price3 = 14.0;
let totalPrice;
const total3 = parseInt("" + qte / 3 + "", 10) * price3;
const total2 = parseInt("" + (qte % 3) / 2 + "", 10) * price2;
const total1 = parseInt("" + ((qte % 3) % 2) + "", 10) * price;
totalPrice = total1 + total2 + total3;
document.getElementById("message").innerHTML =
`Total price is $${totalPrice}`;
what is actually happening in the code
well it is basic mathematics, if you want to know how many 3s in your number you divide by 3 and take the integer part or floor of the result, basic division. for example 10 = 3*3 + 1 so you have 3 as a result of that division.
since you only want to apply the price of 3 pizza as top priority you do this division then multiply by the price for 3.
then come the priority for the price of 2 pizzas, but you not interested for the total number of pizzas, only what was left after you payed with the price of 3 pizzas so you do the mod operator (%) with 3 to get was left unpaid, for example 8 = 3*2 + 2, this give us 2 pizzas left unpaid so you apply the price of 2 pizzas.
the you check if a single pizza is left after you paid for 2 pizzas (which would only happen if only a single pizza was left after you paid for 3). if there is single pizza you pay for it otherwise you add nothing.
ps: after paying for pizzas in multiple of three, you only add the price of 2 pizzas or a single one, but never both, otherwise price of 3 pizzas would apply instead.
hope the explanation is clear, if not leave a comment and i'll try to adjust what was not clear.

Related

How can I display addition operation? [duplicate]

I am creating an seat booking page with html/javascript.
This is part of the criteria I am working on:
When Passengers 1 to 4, Add £0.10 to Fare per mile
When number of miles is less than or equal to 10, then Fare per mile is £1.-
The problem is, is that when I try to add together the total cost + cost for passengers, it concatenates the variable (tried it both ways).
Any help would be greatly appreciated.
function MyFunction() {
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value;
if (isNaN(miles) || miles < 1) {
text = "Input not valid";
} else if (miles <= 10) {
cost = miles;
}
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value;
if (passengers >= 1 && passengers <= 4) {
passengerresponse = "OK";
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}
Journey in miles:
<input id="miles" type="number">
<p id="miles2"></p>
Number of passengers:
<input id="passengers" type="number">
<p id="passengers2"></p>
<button type="button" onclick="MyFunction()">Submit</button>
Total cost:
<p id="totalcost"></p>
passengers is a string, not a number. You're doing the same thing as saying cost = 'Santa' + 'Claus'; The fact that it's cost = '1' + '4'; doesn't change the '1' and '4' to a 1 and 4.
The solution is to use parseInt, Number, or one of the method from this answer.
You should convert passengers to numerical value.
Method 1 + unary oprerator
passengers = +document.getElementById("passengers").value;
Method 2 parseInt()
passengers = +document.getElementById("passengers").value;
passengers = parseInt(passengers, 10);
Cost is undefined if you put any miles in greater than 10. When you add undefined to the number of passengers, the result is Not a Number (NaN).
Also, I would recommend you use parseInt on the data you're retrieving from the inputs. Right now you're pulling them in as strings and doing math on them, which only works because Javascript has been smart enough to implicitly cast them as numeric where necessary.
function MyFunction()
{
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value; // miles is a string
miles = parseInt(miles, 10); // convert to numeric base 10
if (isNaN(miles) || miles < 1)
{
text = "Input not valid";
}
else if (miles <= 10)
{
cost = miles;
}
// if miles > 10, cost is undefined
if(!cost) cost = 0;
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value; // passengers is a string
passengers = parseInt(passengers, 10); // convert passengers to a number
if (passengers >= 1 && passengers <= 4 )
{
passengerresponse = "OK";
console.log(cost, passengers);
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}

Can I force percentages to sum up to a exact value?

I have a fixed tax value, say USD 50,00, and I want to divide this tax among people. So, one person can select how much of the tax he will pay. Once this person selects its quota, the remaining of the tax is divided among the others.
I have made a javascript(I am using EmberJs) function to do this automatically but sometimes the value is evaluated to more than USD 50 and sometimes less.
My function:
percentageFromValue(person, selectedValue){
selectedValue = selectedValue.replace(/[R$\s]/g,'');
selectedValue = selectedValue.replace(/[,]/g,'.');
selectedValue = parseFloat(selectedValue);
let taxValue= this.get('taxValue');
///nao deixar valor utrapasse o valor da taxa
if(selectedValue> taxValue)
valor = taxValue;
let personPercentage = (selectedValue*100.0 / taxValue);
personPercentage = parseFloat(personPercentage );
let parcialSum= 0;
person.set('pctTax',personPercentage.toFixed(2));
let remainingPercent= 100.0 - personPercentage ;
let totalPersons = this.get('persons.length');
let pctPerPerson= remainingPercent/ (totalPersons - 1);
let valuePerPerson= (pctPerPerson* taxValue) / 100.0;
this.get('persons').forEach(r =>{
if(person.get('id') != r.get('id')){
r.set('pctTax',pctPerPerson);
r.set('value',valuePerPerson.toFixed(2));
}
});
},
How Can I make this automatic redistributions to always sum up to USD 50,00??
This is more of a rounding problem than a programming problem.
Say you want to divide a $50 tax among three people... 50/3 = 16.6666666... assuming it's a currency and you round up to two decimals, each person pays $16.66 and the sum is 16.66 * 3 = 49.98.
If there is no requirement of having all people paying the exact same amount of tax every time, I'd just add/subtract the rounding difference from the first person:
let remainingPercent= 100.0 - personPercentage ;
let totalPersons = this.get('persons.length');
let pctPerPerson= remainingPercent/ (totalPersons - 1);
let valuePerPerson= (pctPerPerson* taxValue) / 100.0;
let roundingError = taxValue - pctPerPerson * totalPersons;
this.get('persons').forEach(r =>{
if(person.get('id') != r.get('id')){
r.set('pctTax',pctPerPerson);
if (this.indexOf(r) == 0) {
r.set('value',valuePerPerson.toFixed(2) + roundingError);
} else {
r.set('value',valuePerPerson.toFixed(2));
}
}
});

Why won't my currency conversion javascript program won't run?

I'm creating a Javascript program where the user will be asked how much pounds (£) they'd like to convert into Euros. The program should check if the number of pounds is greater than 0 and a number. If the input is 0 or a negative number or the input is not a number then an error message should be displayed – “input error, please input a number greater than 0”.
If the pounds to be exchanged is > £500 then no commission is charged. If the number of pounds worked is < = £500 then 3% commission is charged.
An output message should be displayed to show the number of euros exchanged.
P.s Amateur js programmer
const exchange = 1.19;
var pounds = 0;
var euros = 0.0;
pounds = prompt("Enter the amount of pounds you wish to convert": );
if (pounds <= 0) {
error_message = ("Input error! Please input a number greater than 0!");
} else if (pounds > 500) {
euros = (pounds * exchange);
alert(euros);
} else {
euros = (pounds * exchange);
euros = (euros - ((euros / 100) * 3));
alert(euros);
}
Everything what you get from the prompt is string.
You can parse your pound into the number with parseInt or parseFloat functions.
const exchange = 1.19;
var euros = 0.0;
var text = prompt("Enter the amount of pounds you wish to convert: ");
const pounds = parseFloat(text);
if (pounds <= 0) {
error_message = ("Input error! Please input a number greater than 0!");
} else if (pounds > 500) {
euros = pounds * exchange;
alert(euros);
} else {
euros = (pounds * exchange);
euros = (euros - ((euros / 100) * 3));
alert(euros);
}
The prompt is a string, as it returns a string (even though ou desire a number)
To convert it, use the Number constructor (or function)
try this:
pounds = prompt("Enter the amount of pounds you wish to convert");
pounds = Number(pounds);
or, you could cast it using the + sign
pounds = +pounds;

Javascript variables not adding two variables correctly, only concatenating

I am creating an seat booking page with html/javascript.
This is part of the criteria I am working on:
When Passengers 1 to 4, Add £0.10 to Fare per mile
When number of miles is less than or equal to 10, then Fare per mile is £1.-
The problem is, is that when I try to add together the total cost + cost for passengers, it concatenates the variable (tried it both ways).
Any help would be greatly appreciated.
function MyFunction() {
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value;
if (isNaN(miles) || miles < 1) {
text = "Input not valid";
} else if (miles <= 10) {
cost = miles;
}
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value;
if (passengers >= 1 && passengers <= 4) {
passengerresponse = "OK";
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}
Journey in miles:
<input id="miles" type="number">
<p id="miles2"></p>
Number of passengers:
<input id="passengers" type="number">
<p id="passengers2"></p>
<button type="button" onclick="MyFunction()">Submit</button>
Total cost:
<p id="totalcost"></p>
passengers is a string, not a number. You're doing the same thing as saying cost = 'Santa' + 'Claus'; The fact that it's cost = '1' + '4'; doesn't change the '1' and '4' to a 1 and 4.
The solution is to use parseInt, Number, or one of the method from this answer.
You should convert passengers to numerical value.
Method 1 + unary oprerator
passengers = +document.getElementById("passengers").value;
Method 2 parseInt()
passengers = +document.getElementById("passengers").value;
passengers = parseInt(passengers, 10);
Cost is undefined if you put any miles in greater than 10. When you add undefined to the number of passengers, the result is Not a Number (NaN).
Also, I would recommend you use parseInt on the data you're retrieving from the inputs. Right now you're pulling them in as strings and doing math on them, which only works because Javascript has been smart enough to implicitly cast them as numeric where necessary.
function MyFunction()
{
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value; // miles is a string
miles = parseInt(miles, 10); // convert to numeric base 10
if (isNaN(miles) || miles < 1)
{
text = "Input not valid";
}
else if (miles <= 10)
{
cost = miles;
}
// if miles > 10, cost is undefined
if(!cost) cost = 0;
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value; // passengers is a string
passengers = parseInt(passengers, 10); // convert passengers to a number
if (passengers >= 1 && passengers <= 4 )
{
passengerresponse = "OK";
console.log(cost, passengers);
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}

Electricity units calculator

I'm basically using functions and if else if statements to build an electricity reading calculator.
The units given is 1236 which is a parameter of the function called elecReading. This will be used as the amount of units used and it will calculate the amount that must be paid.
However, the first 0-500 units are billed at $1 per unit. The next 500-1000 units are billed at $1.10 a unit, and over 1000 units are billed at $3.20 a unit. For example, if I used 1000 units, my bill would be $1050.
I'm unsure how I can get this working without breaking down 1236 into singular numbers manually. How can I write a calculator like this with JavaScript?
Obviously I'm not asking for the complete answer, but a push in the right direction would be very helpful at this stage!
Thanks for the help in advance
The static version would be something like:
var UNIT_PRICE_1001_OVER = 3.20;
var UNIT_PRICE_501_1000 = 1.10;
var UNIT_PRICE_UNDER_500 = 1.00;
function elecReading(units) {
var price = 0;
if (units > 1000) {
price += (units-1000) * UNIT_PRICE_1001_OVER;
units = 1000;
}
if (units > 500) {
price += (units - 500) * UNIT_PRICE_501_1000;
units = 500;
}
price += units * UNIT_PRICE_UNDER_500;
return price;
}
This is assuming the unit price ranges are 1-500, 501-1000, 1001-Inf. Obviously this can be done more generally / with less hardcoding, using a list of objects representing a price range + price per unit in said range.
Try following function. Assuming peak rates are from units 1000+, medium rates from 501-1000, and offpeak rates from 0-500.
You could change the variables names as per your requirements/understanding.
EDITED:
While loop is added to keep reducing total units until they are greater than 1000
function elecReading(units){
var totalUnits=units;
var offPeakRate=1;
var mediumRate=1.10;
var peakRate=3.20;
var totalCharges=0;
if(totalUnits>1000){
PeakUnits = totalUnits-1000;
totalCharges = totalCharges + (PeakUnits * peakRate);
totalUnits = 1000;
}
if(totalUnits > 500){
totalUnits = totalUnits-500;
totalCharges = totalCharges + (totalUnits * mediumRate);
}
totalCharges = totalCharges + (totalUnits * offPeakRate);
return totalCharges;
}
console.log(elecReading(2000));

Categories

Resources