I want to pass in a value, obtained from the an html object, convert that value into an integer so I can run arithmetic on it before outputting it. As my code stands now, it just adds them up like a string. So a value of 5 + a modifier of 100 ends up equaling = 5100, not 105.
Here's my form code:
<form>
Add Amount: <select id="addTweets">
<option value=5>5</option>
<option value=10>10</option>
<option value=15>15</option>
</select>
</br>
<input type="button" value="Add It" onclick="addTweet()" />
</form>
Here's my script:
function addTweet()
{
var mod = 100;
var results = document.getElementById("addTweets").value;
results += mod;
document.getElementById("tweetsOutput").innerHTML = results;
}
The unary plus (+) coerces its operand into a number:
var results = +document.getElementById("addTweets").value;
...
typeof( results ); // number
Use parseInt:
var results = document.getElementById("addTweets").value;
var intResults = parseInt(results, 10) + mod;
You can use parseInt
var results = parseInt(document.getElementById("addTweets").value);
just add parseInt, then you could add it normally
var results = parseInt(document.getElementById("addTweets").value);
EDIT:
parseInt alternate, you can use "|0" use bitwise-or zero
var results = document.getElementById("addTweets").value|0;
Try:
var valResult = document.getElementById("addTweets").value; // get the value of the field
var results = parseInt(valResult) + mod; // convert the value to int to do calculation
document.getElementById("addTweets").value = results; // assign results to the field value
Generally, you can convert the string numerical values into integers by doing a mathematical operation on it:
x = "9"; //String numerical value
y = 10;//integer value
alert(x+y)// output 910;
x = x*1;
alert(x+y) // output 19
Checkout this demo
Related
I need to sum all of the values of a key "number" from several objects within an array. What would be the correct way to do this? This is what I've tried.
var numarray = [{"number":"10"},{"number":"2"},{"number":"5"},
{"number":"3"},{"number":"21"},{"number":"43"},{"number":"30"}];
function Sum() {
var sum;
for (number in numarray[i]){
alert(sum); //sum would be the result I need to get
}
}
Use forEach to loop through each of the json object.
Use parseInt to convert the values to integer
var numarray = [
{"number":"10"},
{"number":"2"},
{"number":"5"},
{"number":"3"},
{"number":"21"},
{"number":"43"},
{"number":"30"}];
function Sum(){
var sum=0;
numarray.forEach(function(item){
sum += parseInt(item.number)
})
document.write('<pre>'+sum+'</pre>')
}
Sum()
DEMO
EDIT
When using parseInt it is better to specify the radix
parseInt(item.number,10)
Using a 10 radix means the number is parsed with a base 10 and thus turns the number into the integer .If parseInt detects a leading zero it will parse the number in octal base
Using Number
Number(item.number)
It will not detect any any octal
You can use reduce for this:
Here's how you would normally find the sum of elements in an array:
var sum = arr.reduce(function(a,b) {
return a + b;
});
Since you have an array of objects, you'll need to change this to something like:
var sum = arr.reduce(function(a,b) {
return parseFloat(a) + parseFloat(b.number);
}, 0);
Notice the 0 I've added added as a parameter? It's the default parameter and required in this case.
When I use prompt() method in JavaScript as follows:
var n=prompt("Enter an integer"); //passing 2 as value
n=(n+n);
document.writeln("n+n value is:"+n);
Then (n+n) gets concatenated as 22 instead of addition as 4
But when I don't use prompt() ie.:
var n=2;
n=(n+n)
document.writeln("n+n value is:"+n);
then it works fine for addition and answer is 4
Why is it so?
prompt("Enter an integer"); returns string
convert it after, you can use parseInt()
var n = parseInt(prompt("Enter an integer"));
SEE FIDDLE DEMO
Use parseInt to convert String to Int
var n = parseInt( prompt("Enter an integer") ); //passing 2 as value
n=(n+n);
document.writeln("n+n value is:"+n);
More info here
A variable declared with datatype var can hold any type of variable which is assigned to it at a moment of time.
eg.
var j = 1; // here j will be an integer datatype and will act as int after this
var j = "1"; //here j will be a string datatype and will act as int after this
in your first case
var n=prompt("Enter an integer");
here a string will be saved in variable 'n'. hence n will act as a string variable. Therefore (n+n) will result in concatenation of two strings.
In your second case
var n = 2;
In here n is holding an integer therefore n acts as int variable.
Thats why (n+n) results into a SUM instead of concatenation.
Change
var n =prompt("Enter an integer")
to
var n = Number( prompt("Enter an integer") )
As if you do console.log(typeof n) you will get a string which means n is actually a string.
So concatenation of
n = '2' + '2';
is '22'
Hence you need to change it to a number. For this you can use Number() or parseInt().
I want to pass in a value, obtained from the an html object, convert that value into an integer so I can run arithmetic on it before outputting it. As my code stands now, it just adds them up like a string. So a value of 5 + a modifier of 100 ends up equaling = 5100, not 105.
Here's my form code:
<form>
Add Amount: <select id="addTweets">
<option value=5>5</option>
<option value=10>10</option>
<option value=15>15</option>
</select>
</br>
<input type="button" value="Add It" onclick="addTweet()" />
</form>
Here's my script:
function addTweet()
{
var mod = 100;
var results = document.getElementById("addTweets").value;
results += mod;
document.getElementById("tweetsOutput").innerHTML = results;
}
The unary plus (+) coerces its operand into a number:
var results = +document.getElementById("addTweets").value;
...
typeof( results ); // number
Use parseInt:
var results = document.getElementById("addTweets").value;
var intResults = parseInt(results, 10) + mod;
You can use parseInt
var results = parseInt(document.getElementById("addTweets").value);
just add parseInt, then you could add it normally
var results = parseInt(document.getElementById("addTweets").value);
EDIT:
parseInt alternate, you can use "|0" use bitwise-or zero
var results = document.getElementById("addTweets").value|0;
Try:
var valResult = document.getElementById("addTweets").value; // get the value of the field
var results = parseInt(valResult) + mod; // convert the value to int to do calculation
document.getElementById("addTweets").value = results; // assign results to the field value
Generally, you can convert the string numerical values into integers by doing a mathematical operation on it:
x = "9"; //String numerical value
y = 10;//integer value
alert(x+y)// output 910;
x = x*1;
alert(x+y) // output 19
Checkout this demo
var number = 342345820139586830203845861938475676
var output = []
var sum = 0;
while (number) {
output.push(number % 10);
number = Math.floor(number/10);
}
output = output.reverse();
function addTerms () {
for (i = 0; i < output.length; i=i+2) {
var term = Math.pow(output[i], output[i+1]);
sum += term;
}
return sum;
}
document.write(output);
document.write("<br>");
document.write(addTerms());
I am trying to take that large number and split it into its digits. Then, find the sum of the the first digit raised to the power of the 2nd, 3rd digit raiseed to the 4th, 5th raised to the 6th and so on. for some reason, my array is returning weird digits, causing my sum to be off. the correct answer is 2517052. Thanks
You're running into precision issues within JavaScript. Just evaluate the current value of number before you start doing anything, and the results may surprise you:
>>> var number = 342345820139586830203845861938475676; number;
3.423458201395868e+35
See also: What is JavaScript's highest integer value that a Number can go to without losing precision?
To resolve your issue, I'd store your input number as an array (or maybe even a string), then pull the digits off of that.
This will solve your calculation with the expected result of 2517052:
var number = "342345820139586830203845861938475676";
var sum = 0;
for(var i=0; i<number.length; i=i+2){
sum += Math.pow(number.charAt(i), number.charAt(i+1));
}
sum;
JavaScript stores numbers in floating point format (commonly double). double can store precisely only 15 digits.
You can use string to store this large number.
As mentioned, this is a problem with numeric precision. It applies to all programming languages that use native numeric formats. Your problem works fine if you use a string instead
var number = '342345820139586830203845861938475676'
var digits = number.split('')
var total = 0
while (digits.length > 1) {
var [n, power] = digits.splice(0, 2)
total += Math.pow(n, power)
}
(the result is 2517052, byt the way!)
Cast the number as a string and then iterate through it doing your math.
var number = "342345820139586830203845861938475676";//number definition
var X = 0;//some iterator
var numberAtX = 0 + number.charAt(X);//number access
The greatest integer supported by Javascript is 9007199254740992. So that only your output is weird.
For Reference go through the link http://ecma262-5.com/ELS5_HTML.htm#Section_8.5
[edit] adjusted the answer based on Borodins comment.
Mmm, I think the result should be 2517052. I'd say this does the same:
var numbers = '342345820139586830203845861938475676'.split('')
,num = numbers.splice(0,2)
,result = Math.pow(num[0],num[1]);
while ( (num = numbers.splice(0,2)) && num.length ){
result += Math.pow(num[0],num[1]);
}
console.log(result); //=> 2517052
The array methods map and reduce are supported in modern browsers,
and could be worth defining in older browsers. This is a good opportunity,
if you haven't used them before.
If you are going to make an array of a string anyway,
match pairs of digits instead of splitting to single digits.
This example takes numbers or strings.
function sumPower(s){
return String(s).match(/\d{2}/g).map(function(itm){
return Math.pow(itm.charAt(0), itm.charAt(1));
}).reduce(function(a, b){
return a+b;
});
}
sumPower('342345820139586830203845861938475676');
alert(sumPower(s))
/*
returned value:(Number)
2517052
*/
Hi i'm trying to do simple addition of two numbers in javascript. When i'm trying to get the two input element values, the result is coming in a concatenation of two numbers
Here is the code:
<html>
<title>
</title>
<head>
<script type="text/javascript">
function loggedUser() {
//Get GUID of logged user
//alert('success');
var x, y , result;
x = document.getElementById('value1').value;
y = document.getElementById('value2').value;
result=x+y;
alert(result);
document.getElementById('res').value = result;
}
</script>
</head>
<body>
<input type="text" id="value1"><br>
<input type="text" id="value2"><br>
<input type="text" id="res">
<input type="submit" value ="submit" onclick=loggedUser();>
</body>
</html>
The "+" operator is overloaded. If any of the parameters is a string, they are all converted to strings and concatenated. If the parameters are numbers, then addition is done. Form control values are always strings.
Convert the parameters to numbers first using one of the following:
x = Number(document.getElementById('value1').value);
or
x = parseInt(document.getElementById('value1').value, 10);
or
x = parsefloat(document.getElementById('value1').value);
or
x = +document.getElementById('value1').value;
or
x = document.getElementById('value1').value * 1;
and so on...
Oh, you can also convert it only when necessary:
result = Number(x) + Number(y);
etc.
The input fields contain strings. If you want to sum two numbers, you have to convert the strings to numbers before adding - otherwise you are just adding two strings. There are lots of ways to do that depending upon what you want to allow. Here's one:
var x, y , result;
x = Number(document.getElementById('value1').value);
y = Number(document.getElementById('value2').value);
result=x+y;
alert(result);
document.getElementById('res').value = result;
See it working here: http://jsfiddle.net/jfriend00/BWW2R/
document.getElementById('').value returns a string. You need to call parseInt on that to make it a number.
It's because x and y are actually strings, not numbers. The value field of the element is always a string, so x+y gives you the concatenation of x and y.
You can parse x and y as integers and add the result of the parsing: that will give you what you want.
The problem is when you take those values you are getting a string and in result you are doing a concatenation. You should use parseInt on both x and y like this:
x = parseInt(document.getElementById('value1').value);
y = parseInt(document.getElementById('value2').value);