Average calculator finding strange and incorrect numbers [duplicate] - javascript

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 3 years ago.
I am trying to make an average calculator. This is my code for it:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
}
var average = total / data.length;
document.write(average);
It seems to take input well, however something goes wrong when it comes to calculation. It says that the average of 6 and 6 is 33, 2 and 2 is 11, and 12 and 6 is 306. These are obviously wrong. Thank you in advance for your help.

You need to take a number, not a string value from the prompt.
The easiest was is to take an unary plus + for converting a number as string to a number
data.push(+newdata);
// ^
Your first example shows, with '6' plus '6', you get '66', instead of 12. The later divsion converts the value to a number, but you get a wrong result with it.

It is taking the input as string. Convert the input to floats before putting them in the array. I think its performing string additions like 6+6=66 and then 66/2 = 33. Similar is the case of 2 and 2.

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?

Convert Google Contact ID to Hex to use in URL

Google Contacts now (Jan 2019) issues a long (19 digit) decimal number id for each contact that you create.
Unfortunately, as discussed in this question the ID cannot be put into a URL to view the contact easily, however if you convert this decimal number to Hex it can be put into the URL.
So the question is, how to convert
c2913347583522826972
to
286E4A310F1EEADC
When I use the Decimal to Hex converter here it gives me
286E4A310F1EEADC if I drop the c (2nd function below is a version of the sites code, but it does use PHP too maybe)
However trying the following functions in Javascript give me mixed results
The first one is from this stack question which is the closest, just 2 digits off
function decimalToHexString(number)
{
number = parseFloat(number);
if (number < 0)
{
number = 0xFFFFFFFF + number + 1;
}
return number.toString(16);
}
console.log(decimalToHexString('2913347583522826972'));
//output 286e4a310f1eea00
function convertDec(inp,outp) {
var pd = '';
var output ;
var input = inp;
for (i=0; i < input.length; i++) {
var e=input[i].charCodeAt(0);var s = "";
output+= e + pd;
}
return output;
}
//return 50574951515255535651535050565054575550
Love to know your thoughts on improving this process
It seems like the limit of digit size. You have to use arrays if you need to convert bigger digits.
You can use hex2dec npm package to convert between hex and dec.
>> converter.decToHex("2913347583522826972", { prefix: false }
//286e4a310f1eeadc
Js example
On python side, you can simply do
dec = 2913347583522826972
// Python implicitly handles prefix
hexa = hex(dec)
print dec == int(hexa, 16)
// True
Python example
For more take a look at the following gist
https://gist.github.com/agirorn/0e740d012b620968225de58859ccef5c

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);

Javascript: For loop, progressive numbers with same digits [duplicate]

This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 6 years ago.
Sorry for the misunderstanding title, I don't know how could explain better.
That's my problem: I have this loop
for(i=1; i<1000; i++){
"MyName_"+i;
}
This will give the following
MyName_1
MyName_2
...
MyName_10
...
MyName_100
How can I do, in a easy way, to have the same number of digits anytime?
This means
MyName_001
...
MyName_010
...
MyName_100
obviously without doing stuff like
if(i<10)
...
if((i>10)&&(i<100))
because the input number is a input so it may be 1000, 10000 or 10000000 and I don't want to write tons of "if()"...
Thank you
Use JavaScript String#slice method
var input = 100; //input any number
var len = input.toString().length;
for (i = 1; i < input; i++) {
console.log("MyName_" + ('000000000000000' + i).slice(-len));
}

Javascript wrong math [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 6 years ago.
I'm not sure what's wrong.
There are two variables, cena and uhrada. cena = 10 and uhrada = 279.8. I want to add them but I am getting 279.810 instead of 289.8.
Thanks for any help!
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = document.getElementById('uhr').value;
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
The reason is that the values you take from the HTML input elements are always strings, even when they look like numbers. You have to first convert them, for instance with parseInt(...) or parseFloat():
var pridatu = parseFloat(uhrada) + parseFloat(cena);
A shorter way is to force conversion with a +:
var pridatu = +uhrada + +cena;
Although this is concise, you should probably first check if the input really is numeric. I refer to a popular question "Validate decimal numbers in JavaScript - IsNumeric()".
You get a string from document.getElementById('uhr').value.
If you want to do math, you need to cast the value either with parseInt(string, 10) or with parseFloat(string) to a number, implicit with a unary plus.
Your code:
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = +document.getElementById('uhr').value; // use implicit cast to number
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
Thats because the values are strings and not numbers.
You have to make them numbers first and then calculate:
var pridatu = parseInt(uhrada) + parseInt(cena);

Categories

Resources