Javascript variables not adding two variables correctly, only concatenating - javascript

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;
}

Related

How can I create a credit card validator using Luhn's algorithm?

I am trying to create a simple credit card validator using Luhn's algorithm. If the check digit matches the last inputted number, then it should alert the user that it is valid. Else, say that it isn't valid. Currently, I am getting an error with my sum (total) coming up as NaN. I assume that is the only problem with the code.
<input type="number" id="creditCard" placeholder="0000 0000 0000 0000">
<input type="submit" id="checkButton" value="CHECK VALIDITY" onclick="checkNumber()">
function checkNumber() {
let number = document.getElementById("creditCard").value;
let multiplier = "212121212121212";
let multipliedNumber;
let multipliedString;
if (number.length != 16) {
alert("Please enter a Credit Card number that is 16 digits in length.");
} else {
for (count = 0; count < number.length - 1; count++) {
multipliedNumber = number[count] * multiplier[count];
console.log(multipliedNumber);
if (multipliedNumber > 9) {
multipliedNumber = multipliedNumber[0] + multipliedNumber[1];
multipliedString = multipliedString + multipliedNumber;
} else {
multipliedString = multipliedString + multipliedNumber;
}
}
console.log(multipliedString);
let checkDigit = 10 - (multipliedString % 10);
if (checkDigit == number[15]) {
alert(`${number} is a valid Credit Card number.`);
} else {
alert(`${number} is not a valid Credit Card number.`);
}
}
}
There are several issues:
multipliedNumber is a product, so it is a number type. Therefore accessing properties like [0] or [1] on it, will just evaluate to undefined. Either turn that value to string first, or (better) use arithmetic to extract the two digits:
multipliedNumber = multipliedNumber % 10 + Math.floor(multipliedNumber/10);
multipliedString is not initialised, so adding things to it will not give the desired outcome. Secondly, you define it as a string, but it should be a number, as with Luhn's algorithm you are supposed to sum up the resulting digits, not concatenate them. So initialise a variable like this:
sum = 0;
... and use it like you did -- although you could benefit from the += operator, and since the operation is the same for both cases, you can do it outside of the if..else blocks.
The calculation of the check digit is wrong when the modulo operation evaluates to 0: 10 - (multipliedString % 10) then returns 10, but in that case the check digit is supposed to be 0. It is much easier to just treat that last digit also in the loop and then check that you have reached a multiple of 10. This is also how the algorithm is explained on Wikipedia
Corrected version:
function checkNumber() {
let number = document.getElementById("creditCard").value;
let multiplier = "2121212121212121"; // One more character added...
let multipliedNumber;
let sum = 0 // Initialise it as a number.
if (number.length != 16) {
console.log("Please enter a Credit Card number that is 16 digits in length.");
} else {
for (count = 0; count < number.length; count++) { // Include last digit in loop
multipliedNumber = number[count] * multiplier[count];
if (multipliedNumber > 9) {
// Use arithmetic to add the two digits
multipliedNumber = multipliedNumber % 10 + Math.floor(multipliedNumber/10);
}
sum += multipliedNumber;
}
let check = sum % 10; // Simpler now because all digits were processed
if (check == 0) { // Sum is multiple of 10
console.log(`${number} is a valid Credit Card number.`);
} else {
console.log(`${number} is not a valid Credit Card number.`);
}
}
}
<input type="number" id="creditCard" placeholder="0000 0000 0000 0000">
<input type="submit" id="checkButton" value="CHECK VALIDITY" onclick="checkNumber()">

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;
}

Application that calculates price depending on quantity in 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.

JavaScript syntax problem - Tip Calculator

Please, could you guys explain this syntax/expression problem?
I was practicing and I tried to create a Tip Calculator which will give me a tip value according to the bill value and percentage.
I can not understand why the expression in the variable finalValues1 does not work.
JSFiddle code result. Thank you very much.
document.getElementById('myForm').addEventListener('submit', function (e) {
e.preventDefault();
var bill, tip, percentage, finalValues1, finalValues2;
bill = document.getElementById('bills').value;
if (bill < 50) { // if bill less $50, give tip of 20%.
percentage = .2;
} else if (bill > 50 && bill < 200) { // if bill greater $50 and less than $200, give tip of 15%.
percentage = .15;
} else {
percentage = .1; // if bill greater than $200, give tip of 10%.
}
tip = bill * percentage;
// I want also to display the final value bills plus tip
finalValues1 = bill + tip; // This code does not work, it is concatenating bills and tip.
finalValues2 = bill * 1 + tip; // this code works and it sums bill plus tip. WHY is that?
document.getElementById('demo').innerHTML = "Tip: " + tip + " and total bill plus tip test1: " + finalValues1 + " test2: " + finalValues2 ;
});
bills.value is a string , not a number
if you want to get a number use bills.valueAsNumber
code:
const myForm = document.getElementById('my-form')
myForm.onsubmit=e=>
{
e.preventDefault()
let bill = myForm.bills.valueAsNumber
, percentage = (bill < 50) ? 0.2 : (bill < 200) ? 0.15 : 0.1
, tip = bill * percentage
;
myForm.demo.textContent = `Tip: ${tip.toFixed(2) } ___ total (bill + tip): ${(bill + tip).toFixed(2)}`
}
<form id="my-form" >
<output name="demo">???</output>
<br>
<br>
<label for="bills">Bill Value :</label>
<input name="bills" autocomplete="off" type="number" required step="0.01">
<br>
<br>
<button type="submit">submit</button>
</form>
as you see it is more easy to use form names instead of elements ID
Use this instead finalValues1 = Math.parseFloat(bill) + Math.parseFloat(tip);
It'll force your code to treat both variables as floats (decimal numbers), rather than strings.
Here is what I would do:
function TipCalc(percent = 20){
this.percent = percent; this.tip = this.total = 0;
this.calc = bill=>{
let t = this.percent/100*bill;
this.tip = t.toFixed(2); this.total = (bill+t).toFixed(2);
return this;
}
}
const tc = new TipCalc;
function billTest(bill){
let p;
if(bill < 50){
p = 20;
}
else if(bill < 200){
p = 15;
}
else{
p = 10;
}
tc.percent = p; tc.calc(bill);
console.log({percent:p, tip:tc.tip, total:tc.total});
}
billTest(15.72); billTest(200.01); billTest(50.01);
Note that tipCalcInstance.tip and tipCalcInstance.total are Strings.
You need to parse the value as a float bill = parseFloat(document.getElementById('bills').value);
And you really should have 0's at the start of your decimals.
You also need to check your order of operations finalValues2 = bill * 1 + tip;
Since multiplication is applied first, this will always just be (bill * 1) + tip.
Change it to bill * (1 + tip)

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;

Categories

Resources