Converting Base 10 to Base 2 in JavaScript Using A While Loop - javascript

I am extremely new to programming and have ran into a slight problem.
I am trying to convert any base 10 number to a base 2 number using JavaScript. In my code I am using "intDividend" to represent any integer between 1 and 1024 that the user inputs into the equation.
I believe I need to use a while loop instead of a for loop, however when I typed everything out, I was not able to get any answer to pop up into the text box I created on my webpage.
I can't figure out what is wrong and nothing I research seems to lead me in the right direction. This is the code that I have come up with.
function Base10ToBase2(intDividend) {
var fltQuotient=1.0
var intQuotient=1
var intRem=0
var fltDiff=0.0
var strB2=" "
while (intDividend != 0) {
fltQuotient=intDividend/2
intQuotient=parseInt(fltQuotient)
fltDiff=fltQuotient-intQuotient
if (fltDiff == 0) {
intRem=0
}
else {
intRem = 1
}
strB2 = intRem + strB2
intDividend=intQuotient
}
ConvertForm.BaseOutput.value=strB2;
}

Related

easy way to multiply a value to successive substrings in javascript

Good morning, sorry for my poor English.
I'm a neophyte and I'm trying to create a javascript program that, given a string in input, if it finds inside defined substrings it returns a value to each substring and returns the sum of the values ​​found as output. Everything ok here. But I'm finding it difficult to manage the case where in front of the substring that I'm looking for, there's for example "2x" which means that the value of the next substring (or of all subsequent substring) is to be multiplied for 2. How can I write in simple code this exception?
Example:
A1 = 1
M1 = 1
input description = A1-M1
output = 2
input descritpion = 2 x A1-M1
output = 4
Thanks in advance
For more comprehesion, you can find my code below:
let str_description = "2 x A1-M1";
var time_mont = [];
var time_cloa = [];
if(str_description.includes("A1")){
time_mont.push (0.62);
} else {
time_mont.push (0);
}
if(str_description.includes("M1")){
time_mont.push (0.6);
} else {
time_mont.push (0);
}
How can I manage "2 x " subtring?

How can I make this Google Apps Script loop efficiently?

I'm making an script that increases the value of a cell by 0.01 until it matches the value of another cell (gets the value, pass through a formula than see if the other cell value matches). The problem is that it takes too long to execute. It was very simple to do on excel, but I don't know how to program in G-Apps Script (neither js).
I guess it's taking too long because it runs on the cloud. There is anyway I can solve it?
Here the code so far:
function Calculate() {
var ss = SpreadsheetApp.getActive();
var vF = ss.getSheetByName('magic').getRange('C31').getValue();
ss.getSheetByName('magic').getRange('C32').setValue(0);
var vE = ss.getSheetByName('magic').getRange('C32').getValue();
var vP
for(vE=0;vE != vP;vE+=0.01){
ss.getSheetByName('magic').getRange('C32').setValue(vE);
var qParc = vF - vE;
ss.getSheetByName('magic').getRange('C3').setValue(qParc);
vP = ss.getSheetByName('magic').getRange('F3').getValue();
}
Thanks in advance!
More likely it's running "too long" because vE != vP is never false, because the kind of floating point used by JavaScript (IEEE-754 double-precision binary floating point, used by most programming languages) is inherently imprecise. Famously, 0.1 + 0.2 is not 0.3 (it's 0.30000000000000004). As a result, it's unreliable to use == or != (or === or !==) with possibly-fractional numbers. (You're okay if they're integers, provided they're not really big ones.)
There probably isn't any need for a loop if you want to update a value to make it match another. Just take the difference and add that to the one you're updating.
But if you do need the loop, replace != with <.
for (vE = 0; vE < vP; vE += 0.01) {
You're also repeating a lot of operations, perhaps expensive ones, there. Once you have the object for (say) a sheet or cell, remember that object reference and reuse it:
function Calculate() {
var ss = SpreadsheetApp.getActive();
var magic = ss.getSheetByName('magic');
var c32 = magic.getRange('C32');
var c3 = magic.getRange('C3');
var f3 = magic.getRange('F3');
var vF = magic.getRange('C31').getValue();
var vE, vP, qParc;
for (vE = 0; vE < vP; vE += 0.01) {
c32.setValue(vE);
qParc = vF - vE;
c3.setValue(qParc);
vP = f3.getValue();
}
}
(I also removed an unnecessary var vE = c32.getValue(); from that, since you immediately overwrite vE with 0 at the beginning of the loop. I just added the declaration to the var declaring vP and, now, qParc.)

Adding space to fill array length

I am working with a javascript program that needs to be formatted a certain way. Basically, I need to have each section of information from an array be a set length, for example 12 characters long, and no more than that.
The problem I am running into comes when a value in the array is NOT 12 characters long. If I have a value that is less than the 12 characters the remaining character allotment needs to be filled with blank spaces.
The length of each section of information varies in size and is not always 12. How can I add X number of blank spaces, should the length not meet the maximum requirement, for each section?
This is where I am at with adding space:
str = str + new Array(str.length).join(' ');
I am pretty sure what I have above is wrong but I believe I am on the right track with the .join function. Any ideas?
EDIT: I was asked to show a wanted outcome. It is a bit complicated because this javascript is being run out of a web report tool and not out of something like Visual Studio so its not traditional JS.
The outcome expected should look something like:
Sample Image
So as shown above the data is in one line, cutting off longer strings of information or filling in blank spaces if its too short for the "column" to keep that nice even look.
try this code and leverage the wonders of the map function:
let say your array is:
var myArr = ["123456789012", "12345678901", "123"];
now just apply this function
myArr.map(function(item){ //evalueate each item inside the array
var strLength = item.length; //apply this function to each item
if (strLength < 12){
return item + ' '.repeat(12-item.length) //add the extra spaces as needed
} else {
return item; // return the item because it's length is 12 or +
}
})
What you are looking for is the ' '.repeat(x) - where x is the times you want to repeat the string you have set, it could be '*'.repeat(2) and you would get '**', if you want to understand more about it look at the docs
depending on which version of javascript, this might work:
if (str.length < 12) str += ' '.repeat(12 - str.length);
Not exactly sure how you're setup -- but something like the following will accept an array and return another array with all its values being 12 characters in length.
var array = ['Test', 'Testing', 'Tested', 'This is not a Test'];
var adjustedArray = correctLength(array, 12);
function correctLength(array, length) {
array.map(function(v, i) {
if (array[i].length < length) {
array[i] += Array((length+1) - array[i].length).join('_');
}
// might not need this if values are already no greater than 12
array[i] = array[i].substring(0, length);
});
return array;
}
console.log(adjustedArray);

I want to obtain a certain part of text from a large webpage using Javascript, how do I?

There is a certain webpage which randomly generates a number, for example "Frequency : 21". I am trying to create a script which takes the number, 21, and compares it to another variable, then to an if else function. Basically, I've completed most of it, but I can't obtain the number 21. And since it is random, I can't put in a fixed value.
Can anyone help me out?
My code goes like:
setTimeout(MyFunction,5000)
function MyFunction(level,legmin) {
var level = x
var legmin = 49
if (level <= legmin) {
location.reload(true)
}
else {
alert("Met requirements.")
}
where the address of the text I want is:
html>body>div#container>div#contentContainer>div#content>
div#scroll>div#scrollContent>div>div>div#pkmnappear>form>p (x in the code above).
A quick-n-dirty solution without regex.
var lookFor = "Frequency : ";
var text = document.querySelector("#pkmnappear>form>p").textContent;
var level = text.substr(text.indexOf(lookFor) + lookFor.length).split(" ")[0];
This assumes the number will be followed by a space

Excel spreadsheet formula to javascript question #2

Hey again everyone. Yet again i am having some problems with trying to get the match correct on this Excel Spreadsheet to JavaScript conversion.
Here is the excel formula:
=IF(IF($B$7=TRUE,$B$28/$B$10,$B$28/$B$5)>1,1,IF($B$7=TRUE,$B$28/$B$10,$B$28/$B$5))
WHERE
B7 = TRUE
B28 = 76800
B10 = 892015
B5 = 999500
And this is my JavaScript i have so far:
function percent(x) { return Math.round((x-0)*100) + '%'; }
if($('#section179').is(':checked'))
{
var percentRepaid = $("#rev3DScanYear").val() / $("#section179Real").val();
if (percentRepaid > 1)
{
$("#paymentCashPer").val('100.00');
}else
{
percentRepaid = $("#rev3DScanYear").val() / $("#SalePrice").val();
$("#paymentCashPer").val(percent(percentRepaid));
}
}else
{
//to be done
}
WHERE
rev3DScanYear = 76800
SalePrice = 999500
section179Real = 892015
For the JavaScript code i keep getting a value of 8% and i should be getting a value of 8.61% as it has on the spreadsheet.
As always, any help would be great! :o)
David
Math.round((x-0)*100) makes x an integer.
You could try Math.round(((x-0)*100)*100)/100 which makes the x = 8.609720... into x=861 and then divides it to get the x=8.61 you're looking for, which is what they would suggest here.
...Also, not really sure why you're subtracting 0 from x...?
Ok, so I've been looking at this again, and I think I didn't look deeply enough the first time.
The logic, if I understand it, is this:
If Section179 is checked then Divisor is Section179Real, else it is SalePrice.
Give me the smaller of 1.00 or (rev3DScanYear / Divisor).
If that's correct, you can do it in excel with =MIN(1,$B28/IF($B$7=TRUE,$B$10,$B$5)) (same references), which means that the following should do what you want it to:
var Divisor = $("#SalePrice");
if($('#section179').is(':checked'))
{
Divisor = $("#section179Real");
}
$("#paymentCashPer").val(Math.round(100*(Math.min(1, $("#rev3DScanYear")/Divisor)*100)/100;

Categories

Resources