1How to hide the output if var m1000 = 0, I want to hide the text1000 for example if i input less than 1000 in the field I want the text1000 or 0 * 1000 Bank Bill to disappear from the output line
function doMoneyExchange() {
var inp1 = parseInt(document.getElementById("input1").value);
var m1000 = parseInt(inp1 / 1000);
var text1000 = m1000 + " * 1000 Bank Bill <br>"
inp1 = inp1 % 1000;
if (m1000 == "0") {
("text1000").hide();
}
var m500 = parseInt(inp1 / 500);
var text500 = m500 + " * 500 Bank Bill <br>"
inp1 = inp1 % 500;
var m100 = parseInt(inp1 / 100);
var text100 = m100 + " * 100 Bank Bill <br>"
inp1 = inp1 % 100;
var out = text1000 + text500 + text100;
document.getElementById("output").innerHTML = out;
It looks like you are trying to use jQuery. Is that correct? ("text1000").hide(); is my evidence. If so, $("text1000").hide(); might work better.
Okay, you're using $.hide() incorrectly. This method is used to hide elements but your program is concatenating everything at the end into a single string, which is then output to an HTML element.
What you should do instead is initialize your string variables to an empty string and then assign them a value on the condition that corresponding number variable is greater than 0. For example,
var text1000 = "";
if(m1000 > 0) {
text1000 = m1000 + " * 1000 Bank Bill <br/>";
}
Rinse and repeat and your resulting output string should only contain lines for numbers greater than 0.
P.S. If you're intent on using string concatenation for your output, there's no need for multiple substring variables. This makes your code less easily maintained. Rather, consider using a single string variable and concatenating in parts rather than all at the end.
var outputString = "";
if(m1000 === "0") {
outputString = outputString.concat(m1000 + " * 1000 Bank Bill <br>";
}
if(m100 === "0") {
outputString = outputString.concat(m100 + " * 100 Bank Bill <br>";
}
// repeat
document.getElementById("output").innerHTML = outputString;
Related
I am trying to make a program which is able to do both decimal to binary and binary to decimal conversions.
I am having trouble with the binary to decimal portion of the code. Forgive me as I know the coding is quite incomplete but I can't figure out where I am going wrong.
Currently I am getting partially correct output in the calculation field (ex. "there is a 1 in the value of (2^0)" and "there is a 2 in the value of (2^1)").
However, when I type 11 as decimal the calculation field is repeating the code twice
(ex. "there is a 1 in the value of (2^0)","there is a 2 in the value of (2^1)","there is a 1 in the value of (2^0)", "there is a 2 in the value of (2^1)").
Obviously it should only give those values once per number.
Also the output field for the actual binary number is incorrect as well, and some of the variables aren't utilized/not needed, but I have been trying to fix the problem of repeating values first before I worked on that.
Any help would be much appreciated!!
function convertByArray(bval) {
var rB = new Array();
var outstr = "";
var p, t, a, o;
o = 0;
for(var i=0; i<bval.length; i++) {
var b = bval.charCodeAt(i);
t = 2;
p = i;
a = t ** p;
if(a === t ** p) {
outstr += a;
}
var bV = b;
$("txtCalc").value += "There is a " + a + " in the value " + "(" + t + "^" + p + ")" + "\n";
o += 1;
b = bV;
$("txtOut").value = outstr;
}
}
You can simply your code if you access the most-significant bit of the bit-string by taking the length (minus one) and subtracting it from the current position. You can access string characters like an array.
var $txtCalc = $(".txtCalc");
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function binaryToDecimal(bval) {
var base = 2, result = 0;
for (var pos = 0; pos < bval.length; pos++) {
var bit = +bval[(bval.length - 1) - pos];
if (bit === 1) {
result += base ** pos;
}
var message = "There is a " + bit + " in the position (" + base + "^" + pos + ")";
$txtCalc.val($txtCalc.val() + message + "\n");
}
$txtOut.val(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />
<br />
<textarea class="txtCalc" rows="10" cols="60"></textarea>
Alternatively, you can simply your program to the following. In JavaScript, you can parse any number in any base and format to another base.
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function convertFromBaseToBase(number, fromBase, toBase) {
return parseInt(number, fromBase).toString(toBase);
}
function binaryToDecimal(bval) {
$txtOut.val(convertFromBaseToBase(bval, 2, 10));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />
I can't get this program to output the average of the entered prompted numbers by a user. How else should i code it? Any help will be appreciated.
var gpas = [];
var gp;
var total = 0;
let count = 0;
var max = 0;
var min = 0;
var out = "";
while (i != "XXX") {
var i = prompt("Enter a gpa or XXX to Stop");
if (i != "XXX") {
gpas.push(i);
}
}
for (var i = 0; i < gpas.length; i++) {
out += gpas[i];
out += "<br/>";
}
count++;
total += gpas[i];
var avg = total / count;
out += avg;
document.getElementById('output').innerHTML += out + "<br/>";
the output is showing "NaN" instead of a valid number.
You can only use a variable that holds the sum of the numbers entered and then just divide it by the total numbers entered.
First approach infinite loop :
The first approach acts as the one you're using. Basically, we'll ask for a new number as long as we don't get the string "XXX".
/**
* #const output the span where to print the average.
**/
const output = document.getElementById('output');
/**
* #var avg stores the sum of the entered numbers.
* #var i keeps track of the number of numbers entered.
**/
let sum = 0,
i = 0;
/** basically while true increment i **/
while (1 && ++i) {
/** ask for a number or "XXX" to exit **/
const n = prompt(`Enter a number or enter "XXX" to exit :`, 0);
/** if "XXX" is entered break the loop (the only way to break that infinite loop) **/
if(n == 'XXX') break;
/** if something else than "XXX" is entered try to cast it to a float **/
sum += parseFloat(n);
}
/** print the average **/
output.textContent = (sum / (i - 1)).toFixed(2); /** why dividing by "i - 1" and not only "i" is because "i" is incremented even when we enter "XXX" **/
<div>average: <span id="output"></span></div>
This approach is not user friendly (the loop can't be exited unless "XXX" is typed) and may consume a lot of resources.
Second approach fixed number of numbers :
This approach asks the user to enter how many number he want to type then we ask him to type as many numbers as the one he typed earlier.
const output = document.getElementById('output');
/**
* #var n the number of numbers the user is going to type.
* #var sum the sum of these numbers.
* #var i a counter used to exit the loop when we reach "n" nummbers typed.
**/
let n = prompt('How many element do you want to enter ?', 2),
sum = 0,
i = 0;
/** while i + 1 < n and no need to manually break the loop **/
while (i++ < n) sum += parseFloat(prompt(`Enter a number (${i} remaining) :`, 0));
output.textContent = (sum / n).toFixed(2); /** now we know how many numbers entered from the beging thanks to the variable "n" **/
<div>average: <span id="output"></span></div>
parseFloat used to parse the numbers (in fact they're strings) entered by the user to floats.
toFixed is used to have only two decimal numbers when calculating the average.
while (i != "XXX") {
var i = prompt("Enter a gpa or XXX to Stop");
if (i != "XXX") {
gpas.push(parseInt(i)); // we need string to number with `parseInt`
}
}
Thanks everyone that contributed. By applying some of the suggestions given, I was able to make it work. I also noticed that the code below does the work too:
var gpas = [];
var gp;
var out = "";
while (i != "XXX")
{
var i = prompt("Enter a gpa or XXX to Stop");
if(i != "XXX"){
gpas.push(parseInt(i));
}
}
let sum = gpas.reduce((a, b) => {
return a + b;
});
sum;
var avg = (sum/gpas.length);
document.getElementById('output').innerHTML += "average =" + avg + "<br/>";
</script>````
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.
I need your help because I'm totally lost with a javascript exercise (I learn alone).
I cut the exercice in steps
I generate an aleatory number between 3 and 20 (with Maths Random)
I generate an array of 100 cells: In each cells, there is one " _ "
If the number is 5: 5 " _ " is aleatory replaced by a " # " (second Maths Random)
I think my cut is good but I can't write it in code.
Before this exercise I've done exercises easier with maths random but now it's more diffult for me.
Some can help me to create the code?
Thank you very much
edit: I tried to do something but without maths random.
function hashtagLine(){
var number = prompt( "Saisissez un nombre entre 3 et 10" );
var line = "";
if (number >= 1 && number <= 10){
for ( var i = 1; i <= 100; i++ ) {
if ( i % number === 0 ) {
line += "#";
} else {
line += "_";
}
}
console.log( line );
} else {
alert( "vous avez entré un nombre qui ne correspond pas" );
}
}
hashtagLine();
Here is a simple implementation:
HTML
<table id="table"></table>
JS
var t = document.getElementById('table');
var rnd = Math.ceil(Math.random() * 17 + 3);
var string = '<tr>';
for (var i = 1; i <= 100; i++) {
if (i == rnd) {
string += '<td>#</td>';
} else {
string += '<td>_</td>';
}
// for new row...
if (i % 10 == 0) {
string += '</tr><tr>';
}
}
string += '</tr>';
t.innerHTML = string;
But if you're trying to learn the language, it's best to try yourself, not just have somebody hand you the answer.
It is still not clear to me what you are trying to achieve, but here is some code that may help you. If you come back with more information then I may be able to help you some more.
Math.random
// get reference to out output element
var pre = document.getElementById('out');
// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function hashtagLine() {
var min = 3,
max = 20,
cells = 100,
number = getRandomInt(min, max + 1),
line = [],
index;
// create the line array of length cells
for (index = 0; index < cells; index += 1) {
// unclear what you are trying to do here!
if (index % number === 0) {
line.push('#');
} else {
line.push('_');
}
}
// output the array as a line of text
pre.textContent += line.join('') + '\n';
}
// Add a click event listener to our generate button
document.getElementById('generate').addEventListener('click', hashtagLine, false);
<button id="generate">Generate</button>
<pre id="out"></pre>
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/