JavaScript conditional statements if/else if/else - javascript

Hello guys! Could you please help me out? I am trying to use certain conditions but they seem to be ignored for some reasons. When I ran the code the popped-up random number given was 93 that fitted in the first declared statement (if), but, It got ignored and moved to the last statement even when true && true.
I do not understand why...
???
function loveMatching (name1, name2) {
name1 = prompt ("Enter your name!");
name2 = prompt ("Enter your crush name!");
if (matchingPercentage() >= 70 && matchingPercentage() <=100) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchingPercentage() + "%. You guys are meant to be together!");
}
else if( matchingPercentage() >=30 && matchingPercentage() <70) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchingPercentage() + "%. Too close to fail!");
}
else {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchingPercentage() + "%. You better look in another direction!");
}
}
function matchingPercentage() {
var n = Math.random();
var n = Math.floor(n * 100) + 1;
return n;
}
loveMatching();

you're calculating a new match % everytime you check it, multiple times in the same conditional. you need to just do it once at the start:
function loveMatching (name1, name2) {
name1 = prompt ("Enter your name!");
name2 = prompt ("Enter your crush name!");
const matchPercent = matchingPercentage(); // call one time
if (matchPercent >= 70 && matchPercent <=100) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchPercent + "%. You guys are meant to be together!");
}
else if( matchPercent >=30 && matchPercent <70) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchPercent + "%. Too close to fail!");
}
else {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchPercent + "%. You better look in another direction!");
}
}

Related

Pop up Alert based on prompt result

I am trying to create an alert based on the answer on the prompt, prompt is working but it does not show the pop up alert message after answering the prompt. Here is my script hoping someone can help please
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.prompt('Please provide your shift on the box below.', ui.ButtonSet.OK);
if (result == "morning") {
alert("We have " + Sheet17.D3 + " OT hours for TLs and " + Sheet17.D11 + " for QAs!");
}
if (result == "dawn") {
alert("We have " + Sheet17.D2 + " OT hours for TLs and " + Sheet17.D10 + " for QAs!");
}
if (result == "EM") {
alert("We have " + Sheet17.D4 + " OT hours for TLs and " + Sheet17.D12 + " for QAs!");
}
if (result == "Mid") {
alert("We have " + Sheet17.D5 + " OT hours for TLs and " + Sheet17.D13 + " for QAs!");
}
if (result == "evening") {
alert("We have " + Sheet17.D6 + " OT hours for TLs and " + Sheet17.D14 + " for QAs!");
}
if (result == "night") {
alert("We have " + Sheet17.D7 + " OT hours for TLs and " + Sheet17.D15 + " for QAs!");
}
}
Tried different scripts but still not working
The script has several problems
It's using a reserved function name that will cause that the script run every time that the spreadsheet is opened. It might work for the spreadsheet owner but it will not work for spreadsheet editors because restrictions introduced by Google several years ago that prevent that a simple on open trigger opens a user interface element.
The variable result has not being declared.
The variable Sheet17 has not being declared.
The variable alert has not being declared.
The following function shows how to use Ui.prompt
function myFunction(){
const ui = SpreadsheetApp.getUi();
const response = ui.prompt('Please provide your shift on the box below.', ui.ButtonSet.OK);
if(response.getResponseText() === 'morning'){
ui.alert('Morning message')
}
}
Note: The code should be added on a script bounded to a spreadsheet.
To learn about how to get values from a spreadsheet please read https://developers.google.com/apps-script/guides/sheets
References
https://developers.google.com/apps-script/reference/base/prompt-response
Try it this way:
function onMyOpen() {
const ui = SpreadsheetApp.getUi();
const result = ui.prompt('Please provide your shift on the box below.', ui.ButtonSet.OK).getResponseText();
const ss = SpreadsheetApp.getActive();
const sh17 = ss.getSheetByName("Sheet17");
const [D2,D3,D4,D5,D6,D7] = sh17.getRange("D2:D7").getValues().flat();
const [D10,D11,D12,D13,D14,D15] = sh17.getRange("D10:D15").getValues().flat();
if (result == "morning") {
alert("We have " + D3 + " OT hours for TLs and " + D11 + " for QAs!");
}
if (result == "dawn") {
alert("We have " + D2 + " OT hours for TLs and " + D10 + " for QAs!");
}
if (result == "EM") {
alert("We have " + D4 + " OT hours for TLs and " + D12 + " for QAs!");
}
if (result == "Mid") {
alert("We have " + D5 + " OT hours for TLs and " + D13 + " for QAs!");
}
if (result == "evening") {
alert("We have " + D6 + " OT hours for TLs and " + D14 + " for QAs!");
}
if (result == "night") {
alert("We have " + D7 + " OT hours for TLs and " + D15 + " for QAs!");
}
}
Run the following function to create installable trigger
function createOnMyOpenTrigger() {
if(ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() == "onMyOpen").length == 0) {
ScriptApp.newTrigger("onMyOpen").forSpreadsheet(ss).onOpen().create();
}
}

how do i get a new number to generate

i need to make a dice rolling program that rolls dice and says who won if it is a tie it rolls again and after each win you earn a point first to 5 wins the game whenever i run mine it uses the same numbers over and over again because it only generated the once how can i fix this and what else do i need to do after this issue to finish the program, thanks for the help!
<script>
var comp1 = Math.floor((Math.random()*6) + 1);
var comp2 = Math.floor((Math.random()*6) + 1);
var you1 = Math.floor((Math.random()*6) + 1);
var you2 = Math.floor((Math.random()*6) + 1);
var counter = 1;
var youPoints = 0;
var mePoints = 0;
while(counter < 6)
{{
alert("Let's shake some dice!")
alert("your turn to roll \n\n you shook a " + you1 + " and a " + you2 + ", so you have " + (you1 + you2));
alert("my turn to roll \n\n I shook a " + comp1 + " and a " + comp2 + ", so I have " + (comp1 + comp2));
counter++
var you = you1 + you2;
var me = comp1 + comp2;
if(you > me)
{
alert("you win " + you + " to " + me);
youPoints++
}
if (me > you)
{
alert("I win " + me + " to " + you);
mePoints++
}
}}
</script>
You're initializing your random variables (you1, you2) outside the while loop.
It's being initialized only once and hence producing the same number every time.
Bring it inside the loop, and that might fix it!
Move the code the generates the random numbers to inside of the loop because, right now, they only generate once... before the loop even starts.
Also, do yourself a favor and use a for counting loop, rather than a while, because while loops are easily misconfigured to cause infinite loops to occur.
var youPoints = 0;
var mePoints = 0;
for(var counter = 1; counter < 6; counter++){
// The code that generates the random numbers has to be in the loop
// in order for new randoms to be generated upon each loop iteration
var comp1 = Math.floor((Math.random()*6) + 1);
var comp2 = Math.floor((Math.random()*6) + 1);
var you1 = Math.floor((Math.random()*6) + 1);
var you2 = Math.floor((Math.random()*6) + 1);
alert("Let's shake some dice!")
alert("your turn to roll \n\n you shook a " + you1 + " and a " + you2 + ", so you have " + (you1 + you2));
alert("my turn to roll \n\n I shook a " + comp1 + " and a " + comp2 + ", so I have " + (comp1 + comp2));
var you = you1 + you2;
var me = comp1 + comp2;
// Don't make two separate if statements. Use one with an else if
if(you > me) {
alert("you win " + you + " to " + me);
youPoints++
} else if (me > you) {
alert("I win " + me + " to " + you);
mePoints++
}
}
Here you go, this should be a complete working example.
Note: I replaced alert() for console.log() so we can see the output here in the console and without popups, but it will work either way.
var compPoints = 0;
var youPoints = 0;
var winnerOfFive = false;
function rollTheDice() {
return Math.floor((Math.random()*6) + 1);
}
function rollAllDice() {
let you1 = rollTheDice();
let you2 = rollTheDice();
let comp1 = rollTheDice();
let comp2 = rollTheDice();
console.log("your turn to roll \n\n you shook a " + you1 + " and a " + you2 + ", so you have " + (you1 + you2));
console.log("my turn to roll \n\n I shook a " + comp1 + " and a " + comp2 + ", so I have " + (comp1 + comp2));
var you = you1 + you2;
var me = comp1 + comp2;
if(you > me) {
console.log("you win " + you + " to " + me);
youPoints++;
} else if(me > you) {
console.log("I win " + me + " to " + you);
compPoints++;
} else {
console.log("It was a tie, no one wins. Re-rolling...");
rollAllDice();
}
}
function startGame() {
while( !winnerOfFive ) {
console.log("Let's shake some dice!")
rollAllDice();
if(compPoints == 5) {
console.log("Comp is first to 5 games and wins " + compPoints + " to " + youPoints);
winnerOfFive = true;
} else if (youPoints == 5) {
console.log("You are first to 5 games and win " + youPoints + " to " + compPoints);
winnerOfFive = true;
}
}
}
// Start the game like this
startGame();

I have a function then a if else statement then a return with a maths in it

// var
var differentBillsInUSD;
// start of bills
differentBillsInUSD = {
firstBill: parseInt(124),
secondBill: parseInt(48),
thirdBill: parseInt(268),
fourthBill: parseInt(180),
fifthBill: parseInt(42),
}
// console to check if everything is alright
console.log(differentBillsInUSD);
console.log("Checking if bill is alright ^");
function calcBill(numberBill) {
if (numberBill < 50) {
return(numberBill + " tip is: " (numberBill*0.20));
} else if (numberBill >= 50 && numberBill <= 200) {
return(numberBill + " tip + total is: " (numberBill*0.15));
} else if (numberBill > 200) {
return(numberBill + " tip + total is: " (numberBill*0.20));
}
}
function calcBillTotal(numberBill) {
if (numberBill < 50) {
return(numberBill + " tip + total is: " ((numberBill*0.20)+numberBill));
} else if (numberBill >= 50 && numberBill <= 200) {
return(numberBill + " tip + total is: " ((numberBill*0.15)+numberBill));
} else if (numberBill > 200) {
return(numberBill + " tip + total is: " ((numberBill*0.20)+numberBill));
}
}
// first bill
console.log(calcBill(differentBillsInUSD.firstBill));
console.log(calcBillTotal(differentBillsInUSD.firstBill));
// second bill
cosnole.log(calcBill(differentBillsInUSD.secondBill));
cosnole.log(calcBillTotal(differentBillsInUSD.secondBill));
ERROR CODE
script.js:21 Uncaught TypeError: " tip + total is: " is not a function
at calcBill (script.js:21)
at script.js:37
It won't work because I am doing to a coding challenge.
It also seems that I am new to javascript.
I tried to do my research, it was very difucult to find.
I am in the middle of code but can not fix.
return(numberBill + " tip is: " + (numberBill*0.20));
you just miss to place a plus sign inside...
return(numberBill + " tip + total is: " (numberBill*0.15));
In JS when you place () after anything it tries to execute it as a function. as you missed the "+" just before "(numberBill*0.15)", so its trying to execute " tip + total is: " as a function. You just need to add a "+"
when you are concatenating a string with a variable , you need to use "+" sign in javascript. Here if you noticed in each if ,else if and else statement you are missing "+" sign.
if (numberBill < 50) {
return(numberBill + " tip is: " + (numberBill*0.20));

scratchpad - Keep getting "undefined" in the output on console.

function largerNum (a,b){
if (a>b){
console.log("The larger number of " +a, "and " +b, "is " +a,".");
}
else{
console.log("The larger number of " +a, "and " +b, "is " +b,".");
}
}
console.log(largerNum (5,12));
the output shows - The larger number of 6 and 12 is 12
undefined
This is because the function is not explicitly returning anything, it return undefined by default
function largerNum(a, b) {
if (a > b) {
console.log("The larger number of " + a, "and " + b, "is " + a, ".");
} else {
console.log("The larger number of " + a, "and " + b, "is " + b, ".");
}
// this function is not returning anything
}
console.log(largerNum(5, 12));
You are not returning any value from your largerNum function so the default return value of undefined is being returned. You could refactor your code like this.
note: the string is concatenated with + rather than using , to separate arguments to console.log
function largerNum(a, b) {
if (a > b) {
return "The larger number of " + a + " and " + b + " is " + a + "."
}
else {
return "The larger number of " + a + " and " + b + " is " + b + "."
}
}
console.log(
largerNum(5, 12)
)
console.log(
largerNum(13, 42)
)
Because you don't need to console.log when invoking the function: your function returns nothing, and you see additional undefined. Just remove console.log() wrapper from console.log(largerNum (5,12)):
function largerNum (a,b){
if (a>b){
console.log("The larger number of " +a, "and " +b, "is " +a,".");
}
else{
console.log("The larger number of " +a, "and " +b, "is " +b,".");
}
}
largerNum(5,12);
Or return the value from function and log the function invocation:
function largerNum (a,b){
if (a>b){
return "The larger number of " +a+ " and " +b+ " is " +a+ ".";
}
else{
return "The larger number of " +a+ " and " +b+ " is " +b+ ".";
}
}
console.log(largerNum(5,12));
Your larger() function doesn't return any values so you are passing null to the last console.log() statement.
function largerNum (a,b){
if (a>b){
return a;
} else {
return b;
}
}
console.log(
"The larger number of " + a + ", and " + b + ", is " +
largerNum(a,b) + "."
);
Should work
because there is no return in your function and so console.log(largerNum (5,12)) gives undefined
make your function to return something
chnage to
function largerNum (a,b){
if (a>b){
return "The larger number of " + a + " and " + b + " is " + a + "."
}
else{
return "The larger number of " + a + " and " + b + " is " + b + "."
}
}
console.log(largerNum (5,12));

how to convert numbers to million in javascript

As in image. for some values converting correctly but some of values not converting... you can see in image
I want to convert numbers to million.I am using Money format function to convert numbers but i am unable to convert numbers.
This is controller part.for some numbers it is converting to millions and for some numbers it is not converting.. Please someone help.
$scope.MoneyFormat = function (labelValue)
{
// Nine Zeroes for Billions
return Math.abs(Number(labelValue)) >= 1.0e+9
? Math.abs(Number(labelValue)) / 1.0e+9 + "B"
// Six Zeroes for Millions
: Math.abs(Number(labelValue)) >= 1.0e+6
? Math.abs(Number(labelValue)) / 1.0e+6 + "M"
// Three Zeroes for Thousands
: Math.abs(Number(labelValue)) >= 1.0e+3
? Math.abs(Number(labelValue)) / 1.0e+3 + "K"
: Math.abs(Number(labelValue));
}
Here I am converting numbers by using Moneyformat. This is controller part where I am converting numbers
$scope.rep.won = $scope.MoneyFormat($scope.rep.won);
$scope.outlook.rem = $scope.MoneyFormat($scope.outlook.rem);
$scope.rep.expectedAmount = $scope.MoneyFormat($scope.rep.expectedAmount);
$scope.rep.potential = $scope.MoneyFormat($scope.rep.potential);
$scope.rep.quota = $scope.MoneyFormat($scope.rep.quota);
I have no idea what $scope.MoneyFormat is.
So I simplified your function to a plain old js function and it works.
function convertToInternationalCurrencySystem (labelValue) {
// Nine Zeroes for Billions
return Math.abs(Number(labelValue)) >= 1.0e+9
? (Math.abs(Number(labelValue)) / 1.0e+9).toFixed(2) + "B"
// Six Zeroes for Millions
: Math.abs(Number(labelValue)) >= 1.0e+6
? (Math.abs(Number(labelValue)) / 1.0e+6).toFixed(2) + "M"
// Three Zeroes for Thousands
: Math.abs(Number(labelValue)) >= 1.0e+3
? (Math.abs(Number(labelValue)) / 1.0e+3).toFixed(2) + "K"
: Math.abs(Number(labelValue));
}
alert( convertToInternationalCurrencySystem (6800000) ); // this outputs 6.8M
JSFiddle: https://jsfiddle.net/r5ju34ey/
getNumber = function(num) {
var units = ["M","B","T","Q"]
var unit = Math.floor((num / 1.0e+1).toFixed(0).toString().length)
var r = unit%3
var x = Math.abs(Number(num))/Number('1.0e+'+(unit-r)).toFixed(2)
return x.toFixed(2)+ ' ' + units[Math.floor(unit / 3) - 2]
}
console.log(getNumber(680000))
console.log(getNumber(6800009))
console.log(getNumber(68000009))
console.log(getNumber(680000000))
console.log(getNumber(6800000000))
console.log(getNumber(68000000000))
console.log(getNumber(680000000000))
console.log(getNumber(6800000000000))
console.log(getNumber(68000000000000))
console.log(getNumber(680000000000000))
console.log(getNumber(6800000000000000))
console.log(getNumber(68000000000000000))
console.log(getNumber(680000000000000000))
I know I'm almost 16 years late at the party, but I can't help myself to comment what I know about it after seeing so much long functions for this task. even the accepted and most upvoted answer uses a quite long function
However, you can use javascript's built-in method Intl (namespace for Internationalization API) here. Intl object has a function named NumberFormat where you can define your preferred language, notation type, and many more. in your use case, the code will look something like
const number = 234234;
const language = "en"
Intl.NumberFormat(language, {notation: "compact"}).format(number) //output - "234K"
check out MDN's doc about Intl and Intl.NumberFormat()
getNumberUnit = function(num, round = 1) {
const unit = Math.floor(Math.round(num / 1.0e+1).toLocaleString().replaceAll(',', '').length),
wunit = ["Thousand","Million","Billion","Trillion","Quadrillion","Quintillion","Sextillion","Septillion","Octillion","Nonillion","Decillion","Undecillion","Duodecillion","Tredecillion","Quattuordecillion","Quindecillion","Sexdecillion","Septemdecillion","Octodecillion","Novemdecillion","Vigintillion","Unvigintillion","Duovigintillion","Trevigintillion","Quattuorvigintillion","Quinvigintillion","Sexvigintillion","Septvigintillion","Octovigintillion","Nonvigintillion","Trigintillion","Untrigintillion","Duotrigintillion"][Math.floor(unit / 3) - 1],
funit = Math.abs(Number(num))/Number('1.0e+'+(unit-unit%3));
return wunit ? funit.toFixed(round).toLocaleString() + ' ' + wunit : num.toFixed(round).toString();
}
var result=getNumberUnit(764000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)
console.log(result)
The best of all
Improving upon the answer to include negatives:
function test(labelValue) {
const sign = Math.sign(Number(labelValue));
// Nine Zeroes for Billions
return Math.abs(Number(labelValue)) >= 1.0e9
? sign * (Math.abs(Number(labelValue)) / 1.0e9) + "B"
: // Six Zeroes for Millions
Math.abs(Number(labelValue)) >= 1.0e6
? sign * (Math.abs(Number(labelValue)) / 1.0e6) + "M"
: // Three Zeroes for Thousands
Math.abs(Number(labelValue)) >= 1.0e3
? sign * (Math.abs(Number(labelValue)) / 1.0e3) + "K"
: Math.abs(Number(labelValue));
}
alert(test(-99998000000));
Because of how far javascript number goes they can only go up to 1e301
This function shows the number in a 3 digit along with a letter, for example 30000000000000000 would be 30,0 Quadrillion and 1000000 would be 1,00 Million.
function simpleNumber(costOfIt, visualOfIt) {
var visualOfIt = costOfIt.toString();
var visualLeng = 6;
var maxLeng = 4;
var letterArrayIndex = 0;
var letterArray = [" Thousand", " Million", " Billion", " Trillion", " Quadrillion", " Quintillion", " Sextillion", " Septillion", " Octillion", " Nonillion", " Decillion", " Undecillion", " Duodecillion", " Tredecillion", " Quatuordecillion", " Quindecillion", " Sexdecillion", " Septendecillion", " Octodecillion", " Novemdecillion", " Vigintillion", " Unvigintillion", " Duovigintillion", " Tresvigintillion", " Quatuorvigintillion", " Quinquavigintillion", " Sesvigintillion", " Septemvigintillion", " Octovigintillion", " Novemvigintillion", " Trigintillion", " Untrigintillion", " Duotrigintillion", " Trestrigintillion", " Quatuortrigintillion", " Quinquatrigintillion", " Sestrigintillion", " Septentrigintillion", " Octotrigintillion", " Novemtrigintillion", " Quadragintillion", " Unquadragintillion", " Duoquadragintillion", " Tresquadragintillion", " Quatuorquadragintillion", " Quinquaquadragintillion", " Sesquadragintillion", " Septemquadragintillion", " Octoquadragintillion", " Novemquadragintillion", " Quinquagintillion", " Unquinquagintillion", " Duoquinquagintillion", " Tresquinquagintillion", " Quatuorquinquagintillion", " Quinquaquinquagintillion", " Sesquinquagintillion", " Septenquinquagintillion", " Octoquinquagintillion", " Novemquinquagintillion", " Sexagintillion", " Unsexagintillion", " Duosexagintillion", " Tressexagintillion", " Quatuorsexagintillion", " Quinquasexagintillion", " Sexasexagintillion", " Septemsexagintillion", " Octosexagintillion", " Novemsexagintillion", " Septuagintillion", " Unseptuagintillion", " Duoseptuagintillion", " Tresseptuagintillion", " Quatuorseptuagintillion", " Quinquaseptuagintillion", " Sexaseptuagintillion", " Septenseptuagintillion", " Octoseptuagintillion", " Novemseptuagintillion", " Octogintillion", " Unoctogintillion", " Duooctogintillion", " Tresoctogintillion", " Quatuoroctogintillion", " Quinquaoctogintillion", " Sesoctogintillion", " Septemoctogintillion", " Octooctogintillion", " Novemoctogintillion", " Nonagintillion", " Unnonagintillion", " Duononagintillion", " Tresnonagintillion", " Quatuornonagintillion", " Quinquanonagintillion", " Sesnonagintillion", " Septemnonagintillion", " Octononagintillion", " Novemnonagintillion", " Centillion", " Uncentillion"];
var leng = 4;
var slic = 1;
for (var g = 0; g < visualOfIt.length; g++) {
if (visualOfIt.length <= visualLeng) {
if (leng < maxLeng) {
leng = maxLeng;
}
if (visualOfIt.length === leng) {
if (slic > 2) {
visualOfIt = costOfIt.toString().slice(0, slic) + letterArray[letterArrayIndex];
break;
} else {
visualOfIt = costOfIt.toString().slice(0, slic) + "," + costOfIt.toString().slice(slic, 3) + letterArray[letterArrayIndex];
break;
}
} else {
leng++;
slic++;
}
} else {
maxLeng += 3;
visualLeng += 3;
letterArrayIndex++;
}
}
return visualOfIt;
}
Just use console.log(simpleNumber(1435345, 0)) outside of the function then it would return 1,43 Million

Categories