How to split $ from javascript value - javascript

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

Related

Why aren't the bigInts adding?

I made a NodeJS program that takes pairs of integers (m, n) as input and prints the sum of their factorials (facm, factn) on the console. I used the BigInteger.js library so that I can calculate using big numbers.
But when I input 20 1, the program just outputs the value of 20! instead of 20! + 1!. It doesn't add. Why?
(For some reason, it works for when the two inputs are the same, for example, 20 20. It also works when the values are smaller.)
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');
var bigInt = require("big-integer");
for (var i = 0; lines[i] != ""; i++) {
var strings = lines[i].split(" ");
var m = parseInt(strings[0]);
var n = parseInt(strings[1]);
var factm = bigInt(1);
var factn = bigInt(1);
for (var a = m; a != 0; a--) {
factm = factm.multiply(a);
}
for (var b = n; b != 0; b--) {
factn = factn.multiply(b);
}
var sum = factm.add(factn);
console.log(sum.toString());
}
Replacing var sum = factm.add(factn) with var sum = factm.add(factn.toString()) solves the problem.

Sum up html string numbers using 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);

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

How to get a numeric value from a string in javascript?

Can anybody tell me how can i get a numeric value from a string containing integer value and characters?
For example,I want to get 45 from
var str="adsd45";
If your string is ugly like "adsdsd45" you can use regex.
var s = 'adsdsd45';
var result = s.match(/([0-9]+)/g);
['45'] // the result, or empty array if not found
You can use regular expression.
var regexp = /\d+/;
var str = "this is string and 989898";
alert (str.match(regexp));
Try this out,
var xText = "asdasd213123asd";
var xArray = xText.split("");
var xResult ="";
for(var i=0;i< xArray.length - 1; i++)
{
if(! isNan(xArray[i])) { xResult += xArray[i]; }
}
alert(+xResult);
var str = "4039";
var num = parseInt(str, 10);
//or:
var num2 = Number(str);
//or: (when string is empty or haven't any digits return 0 instead NaN)
var num3 = ~~str;
var strWithChars = "abc123def";
var num4 = Number(strWithChars.replace(/[^0-9]/,''));

I want to add all the values in the field Sum to the field Total but it is not working

Here, sums[i].value is getting right values but when I want to keep a grand total of all Sum, it is failing.
function calc() {
var amounts = document.getElementsByName("Amount");
var prices = document.getElementsByName("Price");
var sums = document.getElementsByName('Sum');
var tax = document.getElementsByName('Tax');
var total = document.getElementsByName('Total');
for (var i = 0; i < amounts.length; i++) {
sums[i].value = amounts[i].value * prices[i].value;
total[0].value = total[0].value + sums[i].value;
// only this line is not working
}
}
Plain HTML is strings, all the way down, and var amounts = document.getElementsByName("Amount"); followed by amounts.value means you now have string values. Since + is also a string operator, JavaScript will happily turn "2"+"4" into "24", which looks like it did maths, but wrong, when in fact it didn't do math at all.
Convert all values that need to be numbers into numbers, first:
var amounts = document.getElementsByName("Amount");
....
var amount = parseFloat(amounts.value); // NOW it's a number
...
Replace your code with :
for (var i = 0; i < amounts.length; i++) {
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
// only this line is not working
}
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
This should help you.
Remove the .value while adding and multiplying
function test()
{
var amounts = new Array();
amounts[0] = "4";
amounts[1] = "6";
amounts[2] = "10";
var prices = new Array();
prices[0] = "4";
prices[1] = "6";
prices[2] = "10";
var sums = new Array();
var total = 0;
for (var i = 0; i < amounts.length; i++) {
sums[i] = parseInt(amounts[i]) * parseInt(prices[i]);
total= parseInt(total) + parseInt(sums[i]);
// only this line is not working
//alert(total); is 152
}
}

Categories

Resources