Sum up html string numbers using javascript - javascript

Hello I have a function that returns numbers inside a <p> tag with the following format:
<p class="numbers">123 + 456 + 789</p>
Is there any way I can do another function or something in javascript to sum up all the numbers and store it into a variable?
Thanks!

// Grab the element
const para = document.querySelector('.numbers');
// Convert the text content to an array and
// make the text number values into actual numbers
const numbers = para.textContent.split(' + ').map(Number);
// Use `reduce` to sum the numbers
const total = numbers.reduce((p, c) => p + c);
DEMO

This should do it:
var string = "<p class="numbers">123 + 456 + 789</p>";
var numbers = string.split(">")[1].split("<")[0].split("+");
var i = 0;
var sum = 0;
while(i < numbers.length){
sum += parseInt(numbers[i]);
i += 1;
}
return sum;

You can use Array.prototype.reduce()
var n = document.querySelector(".numbers").textContent;
var nums = n.replace(/\s/g, "").match(/^\d+|[+-]\d+/g);
var res = nums.reduce((a, b) => Number(a) + Number(b));
document.body.innerHTML += `=${res}`;
<p class="numbers">123 + 456 + 789</p>

var x = document.querySelector('.numbers').textContent.split("+").map(Number);
var y = x.reduce(function(add,num){return add+num})
console.log(y);

Related

How to perform comma and decimal separation of a number using javascript?

I have a value 2000000 and i want this to be formatted as 2,000,000.00
below is the script i have tried but not able to get the exact output.
function myFunction() {
var num = 2000000;
var c = num.toLocaleString()
var n = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//var number=n.
var number = parseInt(n).toFixed(2);
document.getElementById("demo").innerHTML = n;
document.getElementById("demmo").innerHTML = number;
}
This function gives 2,000,000 and 2.00 but it should be 2,000,000.00
help me to get the required result.
Use toFixed, then add the , and ensure that there are two 0 at the end:
const addTo = (add, length) => str => str.length >= length ? str : addTo(add, length)(str + add);
const chunk = (sym, length) => str => str.length < length ? str : chunk(sym, length)(str.substr(0, str.length - length)) + sym + str.substr(str.length - length);
const [num, fraction] = 2000000..toFixed(2).split(".");
return chunk(",", 3)(num) + "." + addTo("0", 2)(fraction);
You could use the NumberFormat object of the ECMAScript Internationalization API:
let num = 2000000;
let l10nEN = new Intl.NumberFormat("en-US", { minimumFractionDigits: 2 });
console.log(l10nEN.format(num));
Or simply use the toLocaleString() method of the number type:
let num = 2000000;
console.log(num.toLocaleString("en-US", { minimumFractionDigits: 2 }));
function myFunction() {
var num = 2000000.00;
var c = num.toLocaleString();
var substr = c.split('.');
var decimal = substr[1];
var intVal= substr[0];
var n = intVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//var number=n.
var number = n+ decimal;
document.getElementById("demo").innerHTML = n;
document.getElementById("demmo").innerHTML = number;
}
You could use Number.prototype.toLocaleString() and Number.prototype.toFixed() to achieve the required result.
DEMO
let value = 2000000;
value = value.toFixed(2).split('.');
console.log(Number(value[0]).toLocaleString('en') + '.' + value[1]);
value= 2000000.87;
value = value.toFixed(2).split('.');
console.log(Number(value[0]).toLocaleString('en') + '.' + value[1]);
Try this
num.toLocaleString('en', { minimumFractionDigits:2 })

How can I add up two or more array elements (numbers)

I want to add up all of the element from var string to each other.
I did try this but now I want to do this for each element.
var operator = document.getElementById("operation").value;
var number = document.getElementById("numbers").value;
var string = number.split(",");
var number1 = string[0];
var number2 = string[1];
var sum = number1 + number2;
document.getElementById("result").innerHTML = parseInt(sum);
Any help is welcome!
Use reduce() and don't forget to cast your string into int:
var number = "1,2,3,4,5"
var sum = number.split(",").reduce(function (total, num) {
return total + parseInt(num);
}, 0);
You can do R. Saban's way and there are also other ways as well. For example try this:
var start = 0; // Using this to add each element in the array starting from 0, look below
var number = document.getElementById("numbers").value;
var string = number.split(",");
string.forEach(function (num) {
start += parseInt(num);
});
// variable "start" will hold the end result

Sum values from an Array, JavaScript

Prompting the user for many inputs, storing it in an array, then printing summation , average, largest number, smallest number and bigger number than mean number.
I have defined a JavaScript variables called magicnumber which is a new Array , and print the value of array, like this:
var magicnumber = [];
mymagicNumber();
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
//sorted in array
var num = parseInt(magicnumber.push(prompt("Enter data value number " + i)));
var s = magicnumber.join(', ');
}
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + s + "<br>";
}
<div id="demo1"></div>
how I can summation it?
You can use Array#reduce() to get the sum
var magicnumber = [];
mymagicNumber();
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
var promptValue = prompt("Enter data value number " + i);
magicnumber.push(+promptValue);
}
var sum = magicnumber.reduce((a,b)=>{return a+b},0);
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + magicnumber.join(', ');
document.getElementById("sum").innerHTML = "The sum : " + sum;
}
<div id="demo1"></div>
<div id="sum"></div>
Here are 2 more ways to find the summation, without using for loop.
var magicnumber = [];
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
//sorted in array
var num = magicnumber.push(parseInt(prompt("Enter data value number " + i)));
}
var data = magicnumber.join(', ');
var s1 = magicnumber.reduce(function(acc, val) {
return acc + val;
});
var s2 = eval(magicnumber.join("+"));
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + data + "<br>";
document.getElementById("demo2").innerHTML = "Sum is: " + s1 + "<br>";
document.getElementById("demo3").innerHTML = "Sum is: " + eval(s2) + "<br>";
}
mymagicNumber();
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>

How to split $ from javascript value

I want to split the $ symbol from i variable and display the value like 20 not like ,20.
The code I use for this:
<script>
var i = "$20";
var j= "10";
var values=i.split('$');
var v = values;
var sum=parseInt(v)+j;
document.write(sum);
</script>
How do I split the value without comma?
var i = "$20",
j= "10",
v = i.replace(/\D/g,''),
sum = parseInt(v, 10)+parseInt(j, 10);
document.getElementById('output').textContent = sum;
JS Fiddle demo.
Edited (belatedly) to address the problems of that particular regular expression removing any . or , characters (to denote decimals):
var i = "$20.23",
j= "10",
v = i.replace(/[$£€]/g,''),
sum = parseFloat(v) + parseInt(j, 10);
document.getElementById('output').textContent = sum;
JS Fiddle demo.
References:
parseFloat().
parseInt().
String.replace().
Try this:
var i = "$20";
var j = "10";
var values = i.split('$'); // Creates an array like ["", "20"]
var v = values[1]; // Get the 2nd element in the array after split
var sum = parseInt(v, 10) + parseInt(j, 10);
console.log(sum);
Don't parse it just perform the addition directly:
var i = 20;
var j = 10;
var sum = i + j; // use parseInt() if it's defined as a string - see below
// var i = "$20".replace(/\$/g,'');
// var j = "30";
// var sum = parseInt(i) + parseInt(j)
Also if you have to replace some character in a string use replace():
i = i.replace(/\$/g,'')
check this it work fine Demo
var i = "$20";
var j = "10";
var values = i.split('$');
var v = values[1];
var sum = parseInt(v) + parseInt(j);
alert(sum);
Try
var i = "$20"
,j = "10"
,sum = +j + +i.slice(1);
//=> sum = 30

How to use a string as a function in javascript or jquery?

So I was trying to create a function that would put the value of i and j in a string as if it was a function.
Lets say that we have a string = "i+j"
what i want is:
sum = sum + i + j
but currently what happens is
sum = sum + "i + j"
anyone got a solution for this?
var i = 5,
j = 10,
string = "i+j",
sum = 100;
sum = sum + eval(string);
console.log(sum); // output 115
use parseInt() :
sum = sum + parseInt(i) + parseInt(j)

Categories

Resources