Make Dynamic Calculations from Keyboard Input with JavaScript? - javascript

I need a simple calculation script that will take number values entered into an input field and display results dynamically based on predefined set of criteria.
For example, I have a set of fee criteria as follows:
0-150 = No charge
150-300 = Display only fixed monthly fee
300-2500 = multiply by 0.002 + fixed monthly fee - 300 = amount
enter amount more than 2500 = multiply by 0.0015 + fixed monthly fee - 300 = amount
I need the results displayed dynamically as the user is typing in the input, without pressing a button. I want to use JavaScript/jQuery for this.
How can this be done? I find it hard to set up the code. Please, help me out with directions and examples. Or better yet, guide me to the solution that will work as described. Can this be done?
I appreciate your help much and thank you all brave coders taking on this challenge! :)

Got it. So the function is as follows:
function calResult(n){
var fixedMonthlyFee = 9.95;
if(0 <= n && n <= 150){
jQuery("#desc").text("No charge");
}else if(150 <= n && n <= 300) {
jQuery("#desc").text(fixedMonthlyFee);
} else if(300 <= n && n <= 2500) {
jQuery("#desc").text(n * 0.002 * 30 + fixedMonthlyFee);
} else {
jQuery("#desc").text(n * 0.0015 * 30 + fixedMonthlyFee);
}
}
console.log('--No Erros--');
Hope that will be helpful to others!

Related

finding value gained where am I going wrong?

I am trying to write a simple piece of script that will tell me the amount gained from the percentage difference between two values. This is what I have but it doesnt return the correct amounts.
function percentUP (money,newNum,Orignal){
var increase = newNum - Orignal;
var percent = Math.floor(Math.round(increase/Orignal*100));
var gains = Math.round((money/percent)*100);
return "you would make £" + gains + " from your " + "£" + money + " investment"
};
I have been testing it with a simple function of (10,30,10) a 200% increase, which should give me a result that reads:
"you would make £30 from your £10 investment"
but instead I get:
"you would make £5 from your £10 investment"
sorry if this is really obvious, I am just learning right now.
You made a mistake in gains calculation. Your percent is in your example equal 200. You want to multiply money by it and divide by 100.
Your calculation: money / 200 * 100 = money / 2
Expected calcualtion: money * 200 / 100 = money * 2
Corrected code:
function percentUP(money, newNum, orignal) {
var increase = newNum - orignal;
var percent = Math.round(increase / orignal);
var gains = Math.round(money * percent);
return `you would make £${gains} from your £${money} investment`
};
PS You could also remove Math.round call from percent calculation. It just messes accuracy.
Gains calculation seems wrong. It should be Original + (Original * Percent / 100). That should be 10 + (10 * 200/100). You could also use your money variable in the above example instead of Original. I wasn't sure of the difference based on what you are calculating.
Also, not sure what's the purpose of having a percentage in % form, it's simpler to just use the decimal form, ie, 2 instead of 200%. That way you avoid the conversion twice.

How do you set a random probability of a object appearing on screen javascript (for a game)

I want an item to appear every now and then. Usually one item appear that give +10 score but i want a rare item to appear at a random chance that give more points.
Ive already tried something that looks like this except repurposed for what i need
if (Math.random() * 100 < 80) {
sendMessage("hi");
}
else if (Math.random() * 100 < 5) {
sendMessage("bye");
}
I expected for a gold thing to appear but it never did
You should probably first determine what you want the probabilities of these events to be and how frequently you want them to occur.
Presumably you'd have some short time interval between these events, say for example 60 seconds. And then the chance of a rare one could be 5%. So your example at the moment seems to be a bit off because of your else statement.
const rand => Math.rand() * 100;
if(rand() <= 80){
// 80% of any reward appearing
if(rand() <= 5){
// Give the super reward, 5% chance
} else {
// Give the regular reward
}
}
Hope that makes sense.
basically you need to calculate once the random probability and then assign the reward based on your logic.
const normalProbability = 80;
const epicProbability = 5;
const obtainReward = () => {
const calculated = Math.random() * 100;
if (calculated <= normalProbability && calculated > epicProbability) {
console.log(`normal probability to appear a common object... you got ${calculated}%`)
return calculated;
} else if (calculated <= epicProbability) {
console.log(`epic probability to appear a common object, you got ${calculated}%`);
return calculated;
}
console.log(`no reward because you got... ${calculated}%`);
return calculated;
}
console.log("starting the automatic process")
setInterval(() => obtainReward(), 3000);

RegEx for range between 1-999999 and precision upto 2 decimal places

I trying trying to apply RegEx in JavaScript that will allow user to enter ammount of min 1 and max 999999 and if user want to enter ammount in decimal then it will allow user to enter decimal upto precision of 2.
Below are the inputs with their respective result
100: Pass
999999: Pass
100.23: Pass
100.2: Pass
100.234: Fail
This is what I have tried so far ^([1-9][0-9]{0,2}|999999)$), this allow me to enter the amount within 1-999999 but I also want to handle decimal cases.
Maybe this could work?:
^[1-9]\d{0,5}(?:\.\d{1,2})?$
I'd recommend doing it logically;
[0, 0.75, 100, 999999, 999999.75, 100.23, 100.2, 100.234].forEach(i => {
var inRange = i >= 1 && i <= 999999; // check whether in range 1-999999
var inPrecisionRange = i * 100 % 1 == 0; //check whether has at most 2 dec. point
console.log(i + " -> " + (inRange && inPrecisionRange));
});
Much simpler, easier to read and much more maintainable than RegEx IMO

JavaScript: Logical Comparison fails when values have different decimal places

The code below is the beginning of a program that will allow the user to input values and the computer will guess the values. I'm stuck on my input validation. For some reason my input validation passes when I compare numbers with the same decimal places, such as 25 and 49.
Image of passed input validation
However, when I try to compare something like 9 and 25, although the input validation should allow it through, it goes to the else portion of my code. I assume this has something to do with the way JavaScript is interpreting the data type. The code is a bit messy and the program is not complete. The focus is just on the way I'm pulling the values from the HTML and the input validation now. Here's the code.
function runGame() {
//get variables from the input fields in HTML form
var low = document.getElementById('lowNum').value;
var high = document.getElementById('highNum').value;
var guess = document.getElementById('compGuess').value;
//input validation
if (low < high && low > 0 && high <= 50 && guess > 0 && guess <= 10) {
alert("Low number: " + low + "\nHigh Number: " + high + "\nComputer Guesses: " + guess);
document.getElementById("computerGuessVal").innerHTML = getRndInteger(low, high);
} else {
alert("Invalid selection. Make sure that the number range is between 1 and 50 and guesses are higher than zero.");
}
}
function getRndInteger(low, high) {
high = Math.floor(high);
low = Math.ceil(low);
return Math.floor(Math.random() * (high - low + 1)) + low;
}
Update - Solved I added ParseInt to my code after checking the data types
with alert(typeof guess). Here's the working code:
//get variables from the input fields in HTML form and convert to integer
var low = parseInt(document.getElementById('lowNum').value);
var high = parseInt(document.getElementById('highNum').value);
var guess = parseInt(document.getElementById('compGuess').value);
Thanks for the suggestions!

how to check if the price exceeded 600

Class Tutorial – If Statements
A small bakery selling bread to local supermarkets and large convenience stores operates on the following basis:
Orders for fewer than 50 loaves are priced at €1.10 per loaf
Orders for between 50 and 90 loaves inclusive are priced at €0.95 per loaf
Orders above 90 loaves are priced at €0.85 per loaf.
Prompt the user to enter the number of loaves they wish to buy.
Display the total price of the order in a text box
If the order total exceeds €60 then display a message in a text box telling the user they are allowed a 20% discount on any additional order of pancakes.
My question is
is this the answer to this question as i am new to javascript?
if its not could someone provide me with a right answer?
I am struggling to display the answer in textbox and also i am struggling to display message saying you are allowed discount of 20% because i dont know how to check if the price exceeded 600 and one more thing
can you just check the variables i have used if they are ok?
var n = prompt("Check your number", "How many items you want to buy?");
n = parseInt(n);
if (n < 50)
{
alert("Total items you want to buy is = " + n + " The total price for these items is = " + n*1.10 + " Euro");
}
else if (n > 50 && n < 90)
{
alert("Total items you want to buy is = " + n + " The total price for these items is = " + n*0.95 + " Euro");
}
else if (n > 200)
{
alert("Total items you want to buy is = " + n + " The total price for these items is = " + n*0.85 + " Euro");
}
else {
alert("Please enter a valid number");
}
Short answer: no, your script is not correct.
Long answer:
You do not check if n is a positive integer. In case of an error parseInt() returns NaN, you can check for it with isNaN(). You may also strip leading zeros, some older engines (< ECMA-Script 5) might see these numbers as octal otherwise, no matter which base is given as the second argument to parseInt().
n = parseInt(n);
if(isNaN(n) || n <= 0){
alert("We, as the respectable bakery we are, "
+"must insist on positive whole numbers. "
+"Thank you for your patience");
}
else{
// go on with the business
}
You do not offer to sell quantities of exactly 50 of bread and the price-range includes 90 loafs, too. Change the respective line to
if(n >=50 && n<= 90){
// set proper price
}
The 20%-off is for pancakes, not bread, you need to hold the total sum in one variable, let's call it totalSum and at the end of all that mess check for it
if(totalSum >= 60){
aler("You are entitled to a 20% discount for you next purchase of "
+"pancakes! Buy some now, they are really yummy!");
}
Computers are also made to make repetitive tasks simpler. You have three times the same two sentences with the number of items and the sum the single differences. Just put them in variables.
var totalItemString = "Total items you want to buy is = ";
var totalSumString = " The total price for these items in Euro is = ";
NB: it is dangerous to compute in floats wrt. currency. In your case do everything in cents instead of Euros and do the division by 100 only for the print-out. You might use toFixed() for it.
But financial computing is complicated and is in parts even regulated by law (depending on the jurisdiction, of course). Shouldn't bother you at all as a beginner but if you like programming and want to go on with it: do not forget it.

Categories