Javascript issue with code developing a credit card schedule [duplicate] - javascript

This question already has answers here:
Creating multiline strings in JavaScript
(43 answers)
Closed 3 years ago.
I am working on a amortization schedule for a credit card loan. I keep getting one error or another when running the code I've written. It's "Unexpected identifier", to which I can't seem to locate where that is.
Please help me to straighten the code better so it will run the schedule
function displayWelcome() {
var balance = 1500;
var interest = 0.18;
var minimumpaymentRate = 0.02;
console.log("Welcome! \nThis program will determine the time to pay off
a
credit card and the interest paid based on the current balance, the
interest rate, and the monthly payments made.")
console.log("Balance on your credit card: $" + balance.toFixed(2))
console.log("Interest Rate: " + (interest * 100) + "%")
console.log("Assuming a minimum payment of 2% of the balance ($20 min)")
console.log("Your minimum payment would be: $" + minimumPaymentment)
console.log("\nYear Balance Payment # Interest Paid
Minimum Payment")
}
function calculateminimumPaymentment(balance, minimumPaymentRate) {
return Math.max(20, balance * minimumPaymentRate);
}
function generatePaymentId() {
var count = 0;
function paymentId() {
count ++;
return count;
}
return paymentId;
};
function processPaymentSchedule(balance, interest, minimumPayment) {
var id = generatePaymentId();
var year = 1;
var payments = 1;
var interestPaid = 0;
var yearChange;
while (balance > 0) {
yearChange = false;
if (payments % 12 == 0) {
year++
yearChange = true;
}
interestPaid += balance * interest / 12;
balance = Math.max(0, balance - (minimumPayment - balance * interest /
12));
minimumPayment = Math.max(20, balance * minimumPaymentRate);
payments++;
}
}
function displayPayment(pmt){
var pmt = {
balance: 1500,
minimumPaymentRate: 0.02,
interest: 0.18
console.log((yearChange ? year:" ") + " " + pmt.balance + "
"
+ payments + " " + pmt.interest + " " +
pmt.minimumPaymentRate);
return displayPayment
};
}
displayWelcome()
processPaymentSchedule(balance, interest, minimumPayment);
The expected results should be:
An amortization schedule that shows: Year, Balance, Interest
UPDATE:
I have updated with the suggestions listed below, but now am getting this error:
minimumPayment is not defined error

Your code is really buggy. There are several errors:
the multiline string should be created with `` instead of quotes
function displayPayment: move console.log and return outside of an object
declare balance, interest, minimumPayment outside of function so that you can use these variables

Related

Javascript: Question Not being displayed and message when correctly answered or incorrectly answer

In my program, it is supposed to generate 2 random numbers and then the user asked what number do you get if you multiply the numbers. When I tried running it, it does not display the part of the question which tells you what the equation is. I debugged it, but it does not show any issues. I was wondering if anyone can tell me how to solve my problem. I am sorry about any inconvenience, I am new to javascript, so I really need help.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunctions()">Try it</button>
<p id="demo"></p>
<script>
function myFunctions() {
let random1 = Math.floor(Math.random() * 100 + 1);
let random2 = Math.floor(Math.random() * 100 + 1);
let answer = random1 * random2;
let counter = 0;
let max = 5;
while (attempts != answer) {
var attempts = prompt('Please answer what is', random1, '*', random2);
counter += 1;
if (counter > max) {
console.log(
'You have no more tries left.',
'The answer was',
answer,
'.'
);
}
if (attempts == answer) {
console.log(
'Congrats the number was',
answer,
'and it took you',
counter,
'tries!'
);
}
}
}
console.log(myFunctions);
</script>
</body>
</html>
Your function should be like this:
The prompt function has 2 params, the first is required which is the text to display, the second is optional (default text).
also do not use ',' in console.log function to concatenate strings.
function myFunctions() {
let random1 = Math.floor((Math.random() * 100) + 1);
let random2 = Math.floor((Math.random() * 100) + 1);
let answer = random1 * random2;
let counter = 0;
let max = 5;
while (attempts != answer) {
var attempts = prompt("Please answer what is " + random1 + " * " + random2);
counter += 1;
if (counter > max) {
console.log("You have no more tries left. The answer was" + answer +".");
break;
}
if (attempts == answer) {
console.log("Congrats the number was " + answer + " and it took you " + counter + " tries!");
}
}
}
Good luck!

Producing NAN when i need the total

The program needs to generate a random number for the presentValue, months, and interest rate between .1-.10%.
When performing the final calculation I get NaN.
var count = 5;
function futureValue(presentValue, interest, months) {
var step1 = 1 + Number(interest);
var step2 = parseFloat(Math.pow(step1, months));
var step3 = presentValue * step2;
return "The future value is: " + step3;
}
for (i = 0; i < count; i++) {
var presentValue = Math.floor(Math.random() * 100)
var interest = ((Math.random() * .10 - 0.1) + .1).toFixed(2)
var months = Math.floor(Math.random() * 100)
futureValue(presentValue, interest, months)
console.log("The present value is: " + presentValue);
console.log("The interest rate is: " + interest);
console.log("The number of months is: " + months);
console.log(futureValue());
}
You need to pass in the arguments:
console.log(futureValue())
to
console.log(futureValue(presentValue,interest,months))
This line calculates the future value correctly, and does nothing with it.
futureValue(presentValue,interest,months);
This line returns calls the futureValue function with no parameters, which returns NaN and writes the result to the log.
console.log(futureValue());
What you should do is assign the value to a variable, and then log that value:
var futureVal = futureValue(presentValue,interest,months);
console.log(futureVal);
Or just:
console.log(futureValue(presentValue,interest,months));
You are calling futureValue() with no parameters. It returns NaN (Not a Number) because you are making calculations with "undefined" which indeed, is Not a Number,
Try:
var count = 5
function futureValue(presentValue,interest,months){
var step1 = 1 + Number(interest);
var step2 = parseFloat(Math.pow(step1,months));
var step3 = presentValue*step2;
return("The future value is: " + step3);
}
for (i=0;i<count;i++){
var presentValue = Math.floor(Math.random()*100)
var interest = ((Math.random()*.10-0.1)+.1).toFixed(2)
var months = Math.floor(Math.random()*100)
var fv = futureValue(presentValue,interest,months) //save your futureValue in a variable.
console.log("The present value is: " + presentValue);
console.log("The interest rate is: " + interest);
console.log("The number of months is: " + months);
console.log(fv)//log your calculated future value
}
That's because
return("The future value is: " + step3);
Is a string. So, it indeed, is not a number.
You should return JUST the number, then create the string.
Once you call futureValue(presentValue,interest,months) the value disappears. If you want to console.log the result you should store it in a variable and then console.log that.

JavaScript stops execution half way and evaluates wrong answer?, Console.log is correct

I didn't think this was possible until console.log(); shown me that whats happening is impossible.
I can't understand how this is possible it's like those variables are being modified before code execution finishes.
I got this JavaScript code with debugging in it.
It's wrapped in this.
$('#buyAmountInput').keyup(function () {
var buyAmount = parseFloat($(this).val());
var totalPrice = 0;
var max = $(this).attr("max");
var min = $(this).attr("min");
if (buyAmount != $(this).val()) {
if (isNaN(buyAmount)) {
buyAmount = 1;
$(this).val('');
} else {
$(this).val(buyAmount);
}
} else {
if (buyAmount > max) {
buyAmount = max;
$(this).val(buyAmount);
} else if (buyAmount < min) {
buyAmount = min;
//$(this).val(buyAmount);
}
}
totalPrice = buyAmount * unitPrice;
//lots of code trimmed off here.
largessAmount = Math.round(buyAmount * largessRule.rebate) / 100;
////
console.log("Buy amount " + buyAmount + " LargessRebate " + largessRule.rebate);
console.log("Total Price " + totalPrice);
console.log("Largess Amount " + largessAmount);
console.log("New rate " + Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
console.log("No .moneyFormat() New rate " + Number(totalPrice / (buyAmount + largessAmount)));
console.log("( " + totalPrice + " / ( " + buyAmount + " + " + largessAmount + " ))");
////
$('#unitPrice').html(Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
});
Debug looks like this
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.71
No .moneyFormat() New rate 0.7083333333333334
( 4250 / (5000 + 1000))
function fastKeyListener content_script.js:208
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.00 //<- What happened here
No .moneyFormat() New rate 0.00008499830003399932 //<- What happened here
( 4250 / (5000 + 1000)) //<- Third line executed this will give good rate..
Even if the variables are global and this code is in a keypress up jQuery callback function.
The variables are printed before they are executed by console.log() and they are correct but the answer is dead wrong.
Here is the moneyFormat() which I don't think could be the problem could it?
var effective_bit = -2;
Number.prototype.moneyFormat = function () {
var num = this;
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * Math.pow(10, -effective_bit) + 0.50000000001);
cents = num % Math.pow(10, -effective_bit);
num = Math.floor(num / Math.pow(10, -effective_bit)).toString();
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ', ' + num.substring(num.length - (4 * i + 3));
if (effective_bit < 0) {
if (cents < 10 && effective_bit == '-2') cents = "0" + cents;
money = (((sign) ? '' : '-') + num + '.' + cents);
} else {
money = (((sign) ? '' : '-') + num);
}
return money;
};
I didn't post the whole code as it's very large, but you can see it live here
Just put into the Unit to buy of 4999, then scroll to 5000 it's all good.. try putting like 5001 or 50000 it will reset it to 5000 and give wrong answer in the process.
EDIT:
could of simplified the question to why does the console.log() functions evaluate incorrect answer if the same equation generated with the same variables just 1 line after in execution after gives correct answer, even on calculator.
Like some quantum going on here, bear with me there is nothing I could have done from 1 line to another line during that code-execution no breakpoints were set nothing plus those callbacks are functions generated in their own sandbox I believe so they are like ajax threads all working to complete sooner or later they all work separately from each other, so nothing working together here to mess it up. What you think could possibly happen here? some temporarily corruption or something?
This occurs sometimes when doing claulations using string variables.
Try converting the buyAmount and any variable that came from HTML to number before any calculation.
You can use the Number() function or parseFloat().
http://jsfiddle.net/rcdmk/63qas2kw/1/

South African ID Number Validate and Get Age and Gender

I've researched this but none of the code I use seems to work. South African ID numbers contain date of birth and gender. All I want is it to pull in that information and verify it when their ID number is entered into an input field, preferably in jQuery or javascript
Any help is appreciated,
Dawid
You could use Koenyn's regex validation, not so sure how a single-digit number (0-9?) from the input represents the gender but basing on this tool you provided and David Russell's Using Javascript to validate South African ID Numbers, here's an untested attempt:
UPDATE 1:
After following this thread, What is a South African ID number made up of?, I updated my implementation to include the gender and citizenship tests.
UPDATE 2:
Forgot to wrap the month number increment id_month + 1 within the date string fullDate, updating solution with Dawid's fix.
HTML Markup:
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
Javascript:
function Validate() {
// first clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
var idNumber = $('#idnumber').val();
// assume everything is correct and if it later turns out not to be, just set this to false
var correct = true;
//Ref: http://www.sadev.co.za/content/what-south-african-id-number-made
// SA ID Number have to be 13 digits, so check the length
if (idNumber.length != 13 || !isNumber(idNumber)) {
error.append('<p>ID number does not appear to be authentic - input not a valid number</p>');
correct = false;
}
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var fullDate = id_date + "-" + (id_month + 1) + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
error.append('<p>ID number does not appear to be authentic - date part not valid</p>');
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
error.append('<p>ID number does not appear to be authentic - check digit is not valid</p>');
correct = false;
};
// if no error found, hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
$('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p>');
}
// otherwise, show the error
else {
error.css('display', 'block');
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
DEMO: http://jsfiddle.net/chridam/VSKNx/
this is the validation regex we us at our company:
string IdExpression = #"(?<Year>[0-9][0-9])(?<Month>([0][1-9])|([1][0-2]))(?<Day>([0-2][0-9])|([3][0-1]))(?<Gender>[0-9])(?<Series>[0-9]{3})(?<Citizenship>[0-9])(?<Uniform>[0-9])(?<Control>[0-9])";
as far as using regex, it's really simple
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
There is a jQuery plugin that you can use. Check it out at http://www.verifyid.co.za/jqueryid
So there is an issue where if the ID number starts with 0 it gives the year of birth 1901 instead of 2001. #louwki mentioned it in his comment
I'm using your code but running into an issues when adding a id number
010101.... it gives the year of birth 1901 instead of 2001 any work around for this?
I have a work around assuming that there is no one older than a 100 years still alive who wants to get their date
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
// Add a 100 years to the current year if older than 100 years
if(id_year < (new Date()).getFullYear() - 100){
id_year+= 100
}
var fullDate = id_date + "-" + id_month + 1 + "-" + id_year;
DEMO: http://jsfiddle.net/dupies/5fwxvu6d/3/

Calculate a discount factor of 2% per year

I need to write a piece of code that requests a value for the number of years of a contract. Then use a for loop to calculate a discount factor of 2% per year, i.e. if it is a one year contract, the price will be 98% of the full price, if it is a two year contract, the price will be 96% of the full price, and so on.
I seem to be a little stuck and not sure if I have totally grasped what they are asking.
Here is what I have already done:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transition//EN" "http://www.w3.org/TR/xhtml/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type = "text/javascript">
var stringVariable = prompt ("Enter the number of people")
var numberVariable
var loopCounter = prompt ("How many years?");
var numberCount = new Array(100/2);
if (stringVariable <= 30) {
numberVariable = 15*stringVariable;
}
else if (stringVariable> 30 && stringVariable<60) {
numberVariable = 12*stringVariable;
}
else if (stringVariable>60) {
numberVariable =12*stringVariable;
}
alert ("Total cost is: $" + numberVariable);
for (loopCounter = 0; loopCounter <= 4; loopCounter++)
{
document.write("Total discount $" + loopCounter - numberCount[loopCounter] + "<br />");
}
alert ("Total cost is: $" + numberVariable - numberCount);
</script>
</body>
</html>
Thanks in advance for any help.
Your code seems to be fundamentally flawed in a few places, especially your variable names.
Here's how I'd tackle the problem:
// parseInt() converts strings into numbers. 10 is the radix.
var num_people = parseInt(prompt('Enter the number of people'), 10);
var num_years = parseInt(prompt('How many years?'), 10);
// Initialize your variables.
var cost = 0;
var discount = 1.00;
// Your if condition was a bit odd. The second part of it would be
// executed no matter what, so instead of using else if, use an
// else block
if (num_people <= 30) {
cost = 15 * num_people;
} else {
cost = 12 * num_people;
}
alert('Total cost is: $' + cost);
// Here is a for loop. i, j, k, ... are usually
// used as the counter variables
for (var i = 0; i < num_years; i++) {
// Multiplying by 0.98 takes 2% off of the total each time.
discount *= 1.00 - 0.02;
// You fill the rest of this stuff in
document.write('Total discount $' + ... + '<br />');
}
// And this stuff
alert('Total cost is: $' + ...);

Categories