While loop and outputting math operators - javascript

I'm trying to create a while loop that outputs a list of values, adds them together, and outputs a total with an "=" sign at the end
I.e., if the User enters the numbers 5 and 12, the output would show up like this:
5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 = total
This is how my 'while' loop looks right now:
while(enteredNum1 <= enteredNum2){
total += enteredNum1;
document.write(enteredNum1 + " + ");
enteredNum1++;
}
document.write("= " + total);
I know it will always append the " + ", but can anyone point me in the right direction for having the last value show "=" instead of the "+" again?

Alternative;
var numbers = [];
while(enteredNum1 <= enteredNum2){
total += enteredNum1;
numbers.push(enteredNum1++);
}
document.write(numbers.join(" + ") + " = " + total);

Proper way:
list = [];
total = 0;
enteredNum1 = parseInt(enteredNum1); // parseInt only if enteredNum1 can be a string
while(enteredNum1 <= enteredNum2) {
total += enteredNum1;
list.push(enteredNum1);
enteredNum1++;
}
document.write(list.join(" + ") + " = " + total);

Any easy way would be an if statement checking if the loop will continue:
while(enteredNum1 <= enteredNum2) {
total += enteredNum1;
if (enteredNum1 + 1 <= enteredNum2) {
document.write(enteredNum1 + " + ");
} else {
document.write(enteredNum1);
}
enteredNum1++;
}
document.write(" = " + total);
Alternatively, saving the output as a string and taking the "+" off using substring would work as well

This should work:
total += enteredNum1;
document.write(enteredNum1);
enteredNum1++;
while(enteredNum1 <= enteredNum2){
total += enteredNum1;
document.write(" + " + enteredNum1);
enteredNum1++;
}
document.write("= " + total);

Related

Can not add up variables NaN

I couldn't have the variables add up as total and neither could I make them multiply inside the var.
What am I doing wrong?
var order;
var amountsoda;
var amountbeer;
var amountwine;
var total = amountsoda + amountbeer + amountwine;
while (order != "stop") {
order = prompt("What order would you like to add? \n\n soda 2 dollar \n beer 5 dollar \n wine 10 dollar")
if (order == "soda") {
amountsoda = prompt("How much " + order + " would you like to add.");
} else if (order == "beer") {
amountbeer = prompt("How much " + order + " would you like to add.");
} else if (order == "wine") {
amountwine = prompt("How much " + order + " would you like to add.");
}
}
document.write("soda: " + amountsoda + " x 2 =" + amountsoda * 2);
document.write("<br>")
document.write("beer: " + amountbeer + " x 5 =" + amountbeer * 5);
document.write("<br>")
document.write("wine: " + amountwine + " x 10 =" + amountwine * 10);
document.write("<br>")
document.write("total: " + total);
You have to initialize the product-amounts and the total with '0'
You need to add up the total inside the while-loop depending on the product chosen
var order;
var amountsoda = 0;
var amountbeer = 0;
var amountwine = 0;
var total = 0
while (order != "stop"){
order = prompt("What order would you like to add? \n\n soda 2 dollar \n beer 5 dollar \n wine 10 dollar")
if (order == "soda" ){
amountsoda = prompt("How much " + order + " would you like to add.");
total = total + amountsoda * 2;
}
else if (order == "beer"){
amountbeer = prompt("How much " + order + " would you like to add.");
total = total + amountbeer * 5;
}
else if (order == "wine"){
amountwine = prompt("How much " + order + " would you like to add.");
total = total + amountwine * 10;
}
}
document.write ("soda: " + amountsoda + " x 2 =" + amountsoda*2);
document.write ("<br>")
document.write ("beer: " + amountbeer + " x 5 =" + amountbeer*5);
document.write ("<br>")
document.write ("wine: " + amountwine + " x 10 =" + amountwine*10);
document.write ("<br>")
document.write ("total: " + total);

Trying to make loop exit , but it currently just continues looping for 100 times

I am trying to make so when the looping of 100 hits on the character exits the loop when the life dice rolls to 0. How it currently is is all gets looped 100 times. I am not quite sure how I need to go about solving this, any tips would be helpful. My code is below.
function addChar(fname, lname, speed, agility, wep, outfit, mood) {
this.fname = fname;
this.lname = lname;
this.speed = speed;
this.agility = agility;
this.wep = wep;
this.outfit = outfit;
this.mood = mood;
this.special = function(specialMove) {
specialMove();
}
this.jumpKick = function() {
var jmpkckTimes = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write("He jumpkicks " + jmpkckTimes + " times. ");
if (jmpkckTimes > 70) {
document.write("He enters rage mode! ");
} else {
document.write("He does not have enough kicks for rage mode. ");
}
}
this.hits = function() {
var allHits = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write(" He gets attacked for " + allHits + " HP.");
}
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
if (life > 0) {
document.write(" The life dice rolls a " + life + ". You have survived! For now...");
} else {
document.write(" The life dice rolls a " + life + ". You have died!");
}
}
}
var myChar = new addChar('Johhny', 'Kicker', 10, 7, 'Ancient Greataxe', 'Barrows', 'angry');
document.write(myChar.fname + " " + myChar.lname + "'s speed is " + myChar.speed + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s agility is " + myChar.agility + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s weapon of choice is: " + myChar.wep + "<br>");
document.write(myChar.fname + " " + myChar.lname + " feels " + myChar.mood + "<br>");
document.write(myChar.fname + " " + myChar.lname + " attempts his special: ");
myChar.special(myChar.jumpKick)
for (i = 1; i < 101; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
function myOutfit() {
document.getElementById("demo").innerHTML = ("He is wearing " + myChar.outfit)
}
var start = Date.now();
var response = prompt("Do you think my character has what it takes?", "");
var end = Date.now();
var elapsed = (end - start) / 1000;
console.log("You took " + elapsed + " seconds" + " to type: " + response);
You need to have a way to communicate outside of the object, of what is happening inside the object.
For example, when something happens in a function, like lifes() or hits(), you should assign a value to a variable on the object to retain state. That way you can access the state from the for loop.
Example:
this.isAlive = true; // starting condition
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
this.isAlive = (life > 0);
if (this.alive) {
document.write('you survived');
} else {
document.write('you died');
}
Now in your for loop, you can access isAlive:
// loop until 100 attempts or you die, which ever comes first
for (i = 1; i < 101 && myChar.isAlive; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
well in general you can break out of foor loops aswell as prevent further execution of a foor loop and continue the next iteration:
for (var i = 0; i < 10; i++) {
if (i == 4) continue;
if (i == 8) break;
console.log(i);
}
this will basically print: 0, 1, 2, 3, 5, 6, 7
(as you can see it kind of skipped 4)
(it will also work in while / do while loops)
so in your case you could check if the return value of one of your functions is true or false or do some other kind of conditional checking in order to break out of the loop.
or similar to how Rob Brander wrote in his answer:
var maxTurns = 100;
var turns = 0;
while (myChar.isAlive && ++turns <= maxTurns) {
myChar.hits();
myChar.lifes();
}
console.log("character is: " + myChar.isAlive ? "alive" : "dead");
console.log("after: " + turns + " turns.");

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

Implement function array

I have a code for a loto which allows us to find and compare number in a array using loops.I need to update my program so that the work of checking the result is done
by a function called checkNumber. This function should take the customer
number and the array of winning numbers as arguments. The customer number
should be returned from a function called getCustomerNumber. The array of
winning numbers should be returned from a function called
getWinningNumbers. The display of the results should be done by a function
called displayResult(). The whole process should be kicked off by a function
called init. Thank you for your help!
x = checkNumber(12, 17, 24, 37, 38, 43);
function checkNumber() {
for (var i = 0; i < winningNumbers.length && !match ; i++)
if (winningNumbers[i] == customerNumbers) {
match = true;
}
}
}
function getWinningNumbers
function displayResult(){
var message="This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "We have a match and a winner!";
alert(message)
} Else
var message="This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "Sorry you are not a winner this week";
alert(message)
}
}

Compare month in nested object array

The following problem is causing me some headache. I'm building an application to compare transaction data with a list of tenants and what they're supposed to pay for rent.
I've got it running nicely except it compares EACH transaction with the monthly rent. What I want to do is first add all (relevant) transaction amounts per month and then compare them.
Should I just build another nested for-loop to compare all the transaction months before I run this loop? I could potentially drop in years of transaction data making it quite inefficient...
Any tips are greatly appreciated.
var table = "<table><thead><tr><th>Rek</th><th>Name</th><th>Date</th><th>Amount</th><th>Rent</th><th>Diff</th></tr></thead><tbody>";
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < tenant.length; j++) {
if (tenant[j].reks.indexOf(data[i].rek) == -1)
continue;
else {
var diff = tenant[j].rent - data[i].amount; //TODO monthly!!!
var style = " style='background-color: ";
if (diff > 0)
style += "red;'";
else
style += "green;'";
table += "<tr><td>" + data[i].rek
+ "</td><td>" + data[i].name
+ "</td><td>" + (data[i].date.getMonth() + 1) + "-" + data[i].date.getFullYear()
+ "</td><td>€ " + data[i].amount
+ "</td><td>€ " + tenant[j].rent
+ "</td><td" + style
+ ">" + diff
+ "</td></tr>";
}
}
}
table += "</tbody></table>";
$('#top').html(table);

Categories