JS - summing elements of arrays - javascript

I'm trying to make operations with numbers that are stored in arrays, unfortunately they seem to be considered as "text" rather than numbers, so when I do like array1[i] + array2[i], instead of doing 2+3=5 I would get 2+3=23 ...
The values of these arrays come from fields (html)
No idea how to deal with that ;D
Thanks for your help
If you wanna look at my code, here's what it looks like :
var polynome = [];
for (var i=0; i<=degree; ++i) {
polynome[i] = document.getElementById(i).value;
}
var a = document.getElementById("a").value;
var tempArray = [];
var quotient = [];
quotient[degree+1] = 0;
for (var i=degree; i>=0; --i) {
tempArray[i] = a * quotient[i+1];
quotient[i] = polynome[i] + tempArray[i];
}
document.getElementById("result").innerHTML = polynome + "<br>" + tempArray + "<br>" + quotient;

array1[i] contains string and not int so when you are trying both elements with + operator it is concatenating both the values rather of adding them
you need to cast both elements in arrays to integer
try this
parseInt( array1[i] ) + parseInt( array2[i] )

The + punctuator is overloaded an can mean addition, concatenation and conversion to number. To ensure it's interpreted as addition, the operands must be numbers. There are a number of methods to convert strings to numbers, so given:
var a = '2';
var b = '3';
the unary + operator will convert integers and floats, but it's a bit obscure:
+a + +b
parseInt will convert to integers:
parseInt(a, 10) + parseInt(b, 10);
parseFloat will convert integers and floats:
parseFloat(a) + parseFloat(b);
The Number constructor called as a function will convert integers and floats and is semantic:
Number(a) + Number(b);
Finally there is the unary - operator, but it's rarely used since subtraction (like multiplication and division) converts the operands to numbers anyway and it reverses the sign, so to add do:
a - -b

Related

How to make a single string into a multitude of strings?

I have a string called e3 which holds the string 1,2,4,5,3,6. I want to add up all of those numbers up to make the number 21 I was considering doing a for loop for this however I do not know how to turn part of a string into its own value.
I anyone has any better idea of what to do please comment, or answer.
You could use String#split for the string and use Array#reduce for summing.
var e3 = '1,2,4,5,3,6',
sum = e3.split(',').reduce(function (a, b) {
return a + +b; // +b forces b to number
}, 0);
console.log(sum);
If you are sure that it is always a comma separated list of numbers, you could split it on the comma into an array and then use array.reduce() to sum them
var asString = '1,2,4,5,3,6';
var asArray = asString.split(',');
var total = asArray.reduce(function(prev, current){
return prev + parseInt(current, 10);
}, 0);
console.log(total) // outputs 21;
You can do it like this:
var e3 = "1,2,4,5,3,6";
// Split by separator ','
var stringsArr = e3.split(',');
var sum = 0;
// Loop through array of string numbers
stringsArr.forEach(function(str) {
// get Int from a string
var strVal = parseInt(str, 10);
sum += strVal;
});
here's the fiddle
Here is working code to do what you need: https://plnkr.co/edit/8LSkZi0oC8msbHI0qOrz?p=preview
At first you use the split method - this separates a string into an array of strings, based on some separator value. In our case, the separator is a comma, but it could be a blank space or something else:
var testString = '1,2,4,5,3,6';
var separator = ',';
function splitStringOnCommasAndGetArray(string, separator){
var arrayOfStrings = string.split(separator);
return arrayOfStrings;
}
After that, we loop through the array and turn each value into a number. We add the numbers, like so:
function addUpArray(arrayOfStrings){
var totalNumber = 0;
for(var i = 0; i < arrayOfStrings.length; i++){
var currentNum = parseInt(arrayOfStrings[i]);
console.log(currentNum);
totalNumber += currentNum;
}
return totalNumber;
}

Adding values in javascript [duplicate]

This question already has answers here:
Plus Arithmetic Operation
(7 answers)
Closed 8 years ago.
I am trying to add up the 2 values (bold) that are inputed by the user but instead of adding then mathematically (100+1 = 101) it adds them like this (100+1 = 1001).
$('#inputcost').keyup(function(){
var price = $(this).val();
});
function checkboxcost() {
var sum = 0;
var gn, elem;
for (i=0; i<2; i++) {
gn = 'extra'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value); }
}
**var total = (price.value + sum.toFixed(2));
document.getElementById('totalcost').value = "$" + total;**
}
</script>
<input id="totalcost" disabled/>
The problem is, as you suspect, in this line:
var total = (price.value + sum.toFixed(2));
The problem is that .toFixed converts the number to a string for display. So you are trying to add a string to a number, which results in concatenation, not addition.
You want to add the numbers together, then display the sum:
var total = (price.value + sum).toFixed(2);
With that said, I'm not sure where price.value is coming from, so it's possible that's a string too. In which case, convert it with the unary plus + operator:
var total = (+price.value + sum).toFixed(2);
Its treating price.value as String so convert that string to number like:
var total = (Number(price.value) + sum.toFixed(2));
it seems string addition is taking place.
So try converting string numbers to integer using parseInt() like:
var x = parseInt("1")
var y = parseInt("2")
var z = x + y
Try parseInt(price.value) + ...
It's because the types of the operands are strings and the + operator for two strings does concatenation, not addition.
If you convert them to numbers then you'll get a number result:
"1" + "2" == "12"
parseFloat("1") + parseFloat("2") == 3

Javascript add count to a number with comma

So I have this
var str=document.getElementById('elem').innerHTML;
str=parseInt(str)+1;
<span id="elem">1,500</span>
and I can't get it to take the entire number and add one (+1) to the number without taking comma off. Can you suggest something?
Remove the commas by replacing them with an empty string, then you can parse the string.
Remember the second parameter in the parseInt method that specifies the base, so that it doesn't use base 8 for zero padded values.
var num = parseInt(str.replace(/,/g, ''), 10) + 1;
If you want to put the changed number back formatted with commas, you can use:
var s = num.toString();
for (var i = s.length - 3; i > 0; i -= 3) {
s = s.substr(0, i) + ',' + s.substr(i);
}
document.getElementById('elem').innerHTML = s;

Converting string to floating number Javascript

I have a issue using variable in if condition. I have three variable where one is a string type and two more in Json. Here settings.DecimalDigits value is 2 or anything more than 2.
var controlValue = integer + '.' + mantissa;
controlValue = parseFloat(controlValue).toFixed(settings.DecimalDigits);
integer & mantissa will have a certain value which is stored in controlValue as string. controlValue is then compared with other two variables (settings.MaxValue & settings.MinValue) in IF condition but its not going through condition as it type is string type
if (controlValue > settings.MaxValue)
controlValue = settings.MaxValue;
if (controlValue < settings.MinValue)
controlValue = settings.MinValue;
In my parsing all three variables will have three values in floating type
controlValue = 123.23 or 123.00
settings.MaxValue = 99.99
settings.MinValue = -99.99
Please help so that the parsing goes through the IF Condition
.toFixed() turns your number back into a string. If you want it back to a number again, then you need to use parseFloat on it. There are probably better ways to do this, but building on your existing code, you would make controlValue a number that would work in your if statement by calling parseFloat() again like this:
var controlValue = integer + '.' + mantissa;
controlValue = parseFloat(parseFloat(controlValue).toFixed(settings.DecimalDigits));
FYI, it might make more sense to just handle the number entirely as a number rather than go back and forth to strings several times:
var controlValue = parseFloat(integer + '.' + mantissa);
var filter = Math.pow(10, settings.DecimalDigits);
controlValue = Math.round(controlValue * filter) / filter;
or perhaps even just this:
var controlValue = parseFloat(integer + '.' + mantissa.toString().substr(0, settings.DecimalDigits));
jfriend00's answer helped me solve my problem. Solution below:
var controlValue = e.target.value; //get value from input
controlValue = Number(controlValue); //Converting the string to number
// Number format parses through if condition
if (controlValue > settings.MaxValue)
controlValue = Number(settings.MaxValue);
if (controlValue < settings.MinValue)
controlValue = Number(settings.MinValue);
// if the value is having a mantissa 00. It will be rejected by Number() function. So next line its converted again to string format using .toFixed() function.
var controlValue = controlValue.toFixed(settings.DecimalDigits);
// Splitting the value into two parts integer and mantissa
integer = controlValue.split('.')[0];
if (typeof integer == 'undefined' || integer == null || integer == "" || isNaN(integer))
integer = 0;
// settings.DecimalDigits is the variable to set any default number of mantissa required to appear.
mantissa = controlValue.split('.')[1];
if (typeof mantissa == 'undefined') {
mantissa = "";
for (i = 0; i < settings.DecimalDigits; i++)
mantissa += '0';
}
// Finally you have the result
controlValue = integer + '.' + mantissa;

How can I parse a string in Javascript?

I have string looking like this:
01
02
03
99
I'd like to parse these to make them into strings like:
1. 2. 3. 99. etc.
The numbers are a maximum of 2 characters. Also I have to parse some more numbers later in the source string so I would like to learn the substring equivalent in javascript. Can someone give me advice on how I can do. Previously I had been doing it in C# with the following:
int.Parse(RowKey.Substring(0, 2)).ToString() + "."
Thanks
Why, parseInt of course.
// Add 2 until end of string
var originalA = "01020399";
for (var i = 0; i < originalA.length; i += 2)
{
document.write(parseInt(originalA.substr(i, 2), 10) + ". ");
}
// Split on carriage returns
var originalB = "01\n02\n03\n99";
var strArrayB = originalB.split("\n");
for (var i = 0; i < strArrayB.length; i++)
{
document.write(parseInt(strArrayB[i], 10) + ". ");
}
// Replace the leading zero with regular expressions
var originalC = "01\n02\n03\n99";
var strArrayC = originalC.split("\n");
var regExpC = /^0/;
for (var i = 0; i < strArrayC.length; i++)
{
document.write(strArrayC[i].replace(regExpC, "") + ". ");
}
The other notes are that JavaScript is weakly typed, so "a" + 1 returns "a1". Additionally, for substrings you can choose between substring(start, end) and substr(start, length). If you're just trying to pull a single character, "abcdefg"[2] will return "c" (zero-based index, so 2 means the third character). You usually won't have to worry about type-casting when it comes to simple numbers or letters.
http://jsfiddle.net/mbwt4/3/
use parseInt function.
parseInt(09) //this will give you 9
var myString = parseInt("09").toString()+". "+parseInt("08").toString();
string = '01\n02\n03\n99';
array = string.split('\n');
string2 = '';
for (i = 0; i < array.length; i++) {
array[i] = parseInt(array[i]);
string2 += array[i] + '. ';
}
document.write(string2);
var number = parseFloat('0099');
Demo
Substring in JavaScript works like this:
string.substring(from, to);
where from is inclusive and to is exclusive. You can also use slice:
string.slice(from, to)
where from is inclusive and to is exclusive. The difference between slice and substring is with slice you can specify negative numbers. For example, from = -1 indicates the last character. from(-1, -3) would give you the last 2 characters of the string.
With both methods if you don't specify end then you will get all the characters to the end.
Paul
Ii they are always 2 digits how about;
var s = "01020399";
var result = []
for (var i = 0; i < s.length; i+=2)
result.push(parseInt(s.substr(i, 2), 10) + ".")
alert( result[2] ) // 3.
alert( result.join(" ") ) // 1. 2. 3. 99.

Categories

Resources