When calculating values within an Array I am getting this: total = "0212.16967.04".
The correct total in this example is:1179.20
function calculateSum(){
//build array of numbers
amtArray = [];
$('.amount').each(function (index, value) {
amtArray.push($(this).text()||0);
});
//calculate all values and return results
var sum = sumArray(amtArray);
console.log('sum ->', sum)
}
function sumArray(input) {
var total = 0;
for (idx=0; idx <= input.length-1; idx++) {
total += input[idx];
}
return total;
}
calculateSum()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="amount">212.16</div>
<div class="amount">967.04</div>
Should output: 1179.20
You need to cast the value from string to number with an unary plus + (or by using Number or parseFloat, or any other operator which expects a number), otherwise if any of the operands is a string, all parts are treated as string and concatinated.
total += +input[idx];
// ^
The error here is you are concatenating strings, here's a solution:
var array = ["212.16", "967.04"]
function sumArray(input) {
var total = 0;
for (idx = 0; idx <= input.length - 1; idx++) {
total += parseFloat(input[idx]);
}
return total;
}
console.log(sumArray(array));
In the function sumArray you can directly return the result of Array.prototype.reduce() using Number to work with numerical values:
const sumArray = arr => arr.reduce((a, b) => a + Number(b), 0);
console.log(sumArray(["212.16", "967.04"]));
You are concatenating string values rather than adding flowing pointing numbers. You can use parseFloat() to convert from string to float like this this:
function sumArray(input) { //input = (2) ["212.16", "967.04"]
var total = 0;
for (idx=0; idx <= input.length-1; idx++) {
total += parseFloat(input[idx]);
}
return total;
}
Aside from using a unary, parsefloat, Number you should also use toPrecision to get that last zero you indicated in your question
var val = document.getElementsByClassName('amount');
function calculateSum() {
var total = 0;
for (var i = 0; i < val.length; i++) {
var value = val[i].textContent;
total += +value;
}
return total.toPrecision(6);
}
val[1].insertAdjacentHTML('afterend', calculateSum());
<div class="amount">212.16</div>
<div class="amount">967.04</div>
Related
I am trying to get the innerHTML of all elements with classname "money" and sum it. But when I am retrieving it with my code it will place all the digits next to eachother.
var elements = document.getElementsByClassName("money");
var arr = new Array(elements.length);
var total = 0;
for (var i=0; i< arr.length; i++){
var val = elements[i].innerHTML;
console.log(val);
total += parseFloat(val).toFixed(2)
}
console.log(total);
The result I'm getting is the following:
image of result
How can I solve this?
toFixed() is converting a number to a string. So you add strings which leads to concatenating.
Sum everything and use toFixed() after you have the final value or use Math.round()
toFixed() returns a string. Parse it (with a unary plus operator), then add to total:
var elements = document.getElementsByClassName("money");
var arr = new Array(elements.length);
var total = 0;
for (var i = 0; i < arr.length; i++) {
var val = elements[i].innerHTML;
console.log(val);
total += +parseFloat(val).toFixed(2)
}
console.log(total);
<div class="money">100</div>
<div class="money">200</div>
<div class="money">300</div>
For non-negative integers num1 and num2, represented as strings, return the sum of num1 and num2.
My solution was to create a filter that has the indexOf with a value of the numbers.
const addStrings = function(num1, num2) {
let filter = "0123456789";
let x = 0;
for(let i=0; i<num1.length; i++) {
x = x + (filter.indexOf(num1[i]) * Math.pow(10, num1.length-1-i));
}
let y = 0;
for(i=0; i<num2.length; i++) {
y = y + (filter.indexOf(num2[i]) * Math.pow(10, num2.length-1-i));
}
return (x+y).toString();
};
It work in most of the cases. However, if the inputs are:
"9333852702227987"
"85731737104263"
It will return the wrong sum: "9419584439332252". I can't understand why it is converting the numbers wrongly.
I've created an object whose keys are digit1, digit2, and carry - all as strings.
The function takes two stringed numbers and adds them "digit by digit" (actually, character by character, as keys to object + carry).
The limit on the "numbers" is the limit on the length of string (minus 1 for the carry).
This could even be adapted to deal with decimals (I leave that to you).
Here's my code:
var sumObject={};
for(var i=0; i<=9; i++) {
for(var j=0; j<=9; j++) {
var sum, carry, digit, obj;
sum=i+j;
carry=sum>9?"1":"0";
digit=sum%10;
obj={sum:""+digit, carry:carry};
sumObject[""+i+j+"0"]=obj;
sum=i+j+1;
carry=sum>9?"1":"0";
digit=sum%10;
obj={sum:""+digit, carry:carry};
sumObject[""+i+j+"1"]=obj;
}
}
function sum2StringedNumbers(sn1, sn2) {
var answer="";
var maxLength=Math.max(sn1.length, sn2.length);
sn1=("0".repeat(maxLength)+sn1).slice(-maxLength);
sn2=("0".repeat(maxLength)+sn2).slice(-maxLength);
var carry="0";
for(var i=maxLength; i>0; i--) {
var key=""+sn1.charAt(i-1)+sn2.charAt(i-1)+carry;
var answer=sumObject[key].sum+answer;
carry=sumObject[key].carry;
}
if(carry=="1") answer="1"+answer;
return answer;
}
The sum of those numbers is larger than Number.MAX_SAFE_INTEGER. You need to use BigInts instead.
const addStrings = function(num1, num2) {
let filter = "0123456789";
let x = 0n;
for(let i=0; i<num1.length; i++) {
x = x + (BigInt(filter.indexOf(num1[i])) * 10n ** BigInt(num1.length-1-i));
}
let y = 0n;
for(i=0; i<num2.length; i++) {
y = y + (BigInt(filter.indexOf(num2[i])) * 10n ** BigInt(num2.length-1-i));
}
return (x+y).toString();
};
console.log(addStrings("9333852702227987","85731737104263"));
You can skip a lot of that code and convert your string directly to a BigInt and calculate from there. Then use toString() to bring it back to a string. Check it out:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
(BigInt("9333852702227987") + BigInt("85731737104263")).toString();
// 9419584439332250
I am trying to create an application that calculates the sum and average of numbers that are inputted into a text field separated by spaces.
I am stuck on the part where you have to put in a loop to calculate the sum and avg from the spaced inputs. I have been using console.log to test throughout while I type my code.
Any guidance would be helpful. First time doing javascript. I have looked at the forms on this website and it seems like all the sum/avg javascript questions arent input text based. That is why I am creating a new question.
HTML and Javascript is Below
<body>
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
</body>
Javascript
function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split(" ");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
//loop input array and sum
for (var i=0; i<arr.length; i++){
sum += arr[i];
}
console.log(sum);
//divded by
//calculate avg divided by myarray.length
//output to div
}
// Here is your function:
/*function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split(" ");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
//loop input array and sum
for (var i=0; i<arr.length; i++){
sum += arr[i];
}
console.log(sum);
//divded by
//calculate avg divided by myarray.length
//output to div
}*/
// Here is a way to do it functionally:
function calculateSumAverage() {
// This is the string that contains the numbers separated by a space.
var inputValue = document.getElementById('numberSeries').value;
var values = inputValue.split(' ')
.map((val) => parseInt(val))
.filter((val) => !isNaN(val));
var sum = values.reduce((currentVal, nextVal) => currentVal + nextVal, 0);
document.getElementById('calculationOutput').innerHTML = `Average: ${sum / values.length}`;
}
<body>
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
</body>
You code is fine except sum += parseInt(arr[i]); you need to parse each string input to integer
input type="text" will give a string.Also to split this string ,use var arr = numberSeries.split(""); , note there is no space between the quotes. To convert each string to number use unary operator.
sum += +arr[i]; The plus(+) sign before arr[i] will convert a string to number.Unless you convert to number , the string concatenation will produce like this 0123...
function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split("");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
console.log(arr)
//loop input array and sum
for (var i = 0; i < arr.length; i++) {
sum += +arr[i];
}
console.log(sum);
}
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
Try like this
function calculateSumAverage()
{
var numberSeries = document.getElementById("numberSeries").value;
var arr = numberSeries.split("");
var sum = 0;
var avg = 0;
for (var i = 0; i < arr.length; i++)
{
sum += parseInt(arr[i]);
}
}
I have the following JSON array:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
How can I calculate all the "price" values together? The result should be 8.
I have so far the following but problems accessing the price items:
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum = sum + fruits[i][price];
}
return sum;
}
console.log(count(fruits)
Thank you!
You need to access them like:
fruits[i].price
and then convert them to numbers before adding them:
parseInt(fruits[i].price, 10);
Final code:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
var total = 0;
for(var i=0; i<fruits.length; i++){
total += parseInt(fruits[i].price, 10);
}
alert(total); //8
See the DEMO here
Two things:
The line
sum = sum + fruits[i][price];
should be
sum = sum + fruits[i].price;
or even
sum += fruits[i].price;
Your code was trying to use a variable called price, not the price property of the fruit entry.
Your prices are strings, so we want to make sure they're converted to numbers when summing them up. You have lots of options there: Apply a unary + to them, pass them into Number(), or use parseInt(..., 10). Below I'll go with a unary +, but there are pluses (no pun!) and minuses to each.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum += +fruits[i].price; // <=== change is here
}
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
With ES5's array additions (which can be shimmed on older browsers), you can do this with either forEach or reduce:
forEach:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
fruits.forEach(function(fruit) {
sum += +fruit.price;
});
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
reduce:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
sum = fruits.reduce(function(prev, fruit) {
return prev + +fruit.price;
}, 0);
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Your code has 2 errors:
To access the price property
fruits[i][price]
should be
fruits[i]['price'] or fruits[i].price
The price property is of type string. So the '+' operator will concatenate the price strings. To add them together you need to change their type to number by doing
parseInt(fruits[i]['price'], 10) or +fruits[i]['price']
If the price property doesn't contain a valid number the result will be NaN (not a number). You could avoid that by using the or operator.
+fruits[i]['price'] || 0
Using the ES5 Array extensions supported by all modern browsers you could write
fruits.reduce(function(m,v) { return m + (+v.price);}, 0);
With ES6 in future browsers this could be reduced to
fruits.reduce((m,v) => m + (+v.price), 0);
You have some errors in your code.
The first one is here: sum = sum + fruits[i][price];
you are trying to use a variable called price, not the property price of the object. You can access to the property using fruits[i]["price"] or fruits[i].price.
To obtain a number, when you are doing the sum, you need to convert the strings in numbers, to do that you can use parseInt(fruits[i]["price"]);. Last error in the last line you forgot the parenthesis and semicolon.
JSFiddle
your function is OK, just add parseInt for it to convert to type int, and has a incorrect syntax in fruits[i][price].
You've two option:
fruits[i]["price"]
OR
fruits[i].price
In my opinion, I would add a small logic code to check if it's a number or not. and return 0 if input data is undefined or null.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(data) {
var sum = 0;
if(data === void 0 ) return 0; // no array input
data.forEach(function(fruit) {
console.log(fruit);
sum += parseInt(fruit.price || 0 ); // if price is undefined, null or NaN, return 0
})
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
You should try this simple code snippet.
You don't need jQuery to do this operation. Simple JS would do.
var sum = 0;
for(var item in fruits){
sum += ~~(fruits[item].price)
}
console.log(sum)
Cheers!
I have a list of numbers such as
var list = ["123","12345678","123","234,2345","2.34567","123.12345","-123","-0.1234","-324215.45"];
This list can have negative, positive numbers with optional decimal values, also negative or positive.
I need to use regular expressions to do 3 things:
getAllNumbersBeforeValue(value);
getAllNumbersAfterValue(value);
getRangeBetweenValues(valueFrom, valueTo);
Value passed in is not known, could be any number.
Update 1:
I've got this, which isn't perfect but works on some numbers:
var a = function(rand) {
var val = "";
var numArr = rand.split("");
for(var i = 0; i < numArr.length; i++) {
val = val + (Number(numArr[i])+1);
}
return "^[^" + val.split("").join("-9][^") + "-9]$"
}; // outputs "^[^2-9][^3-9][^4-9][^5-9][^6-9]$" with rand "12345"
Im trying to get a regular expression programmatically generated from a given value
For example "123456" is a random number (rand), I would like to be able to filter an array of numbers for values that are higher then rand (or lower then rand) using a regex value.
Thanks
You could use underscore.js (http://underscorejs.org) to filter your results. For example...
var list = ["123","12345678","123","234,2345","2.34567","123.12345","-123","-0.1234","-324215.45"];
function getAllNumbersBeforeValue(list, value) {
return _.filter(list, function(num) {
return num < value;
});
}
Here's an example without using a framework...
function getAllNumbersBeforeValue(list, value) {
var output = [];
for(var i = 0; i < list.length; i++) {
if(list[i] < value) {
output.push(list[i]);
}
}
return output;
}
getAllNumbersBeforeValue(list, 123);