Get id as a number in javascript..? - javascript

A simple question..
var x = document.getElementById('xNum');
var y = document.getElementById('xNum');
var result = x * y;
document.write(result);
and
<div id="xNum">20</div>
<div id="yNum">50</div>
It displays 20 and 50. why not calculating 20 * 50? Why does it get as a integer or how can I get numbers in an div?
Thanx!
I don't get any result with that:
var x = document.getElementById('xNum').innerHTML;
var y = document.getElementById('xNum').innerHTML;
var result = parseInt(x) * parseInt(y);
document.write(result);

Use parseInt and process it on their HTML,
var result = parseInt(x.innerHTML) * parseInt(y.innerHTML)
If you don't need to support browsers priot to IE9, you should use textContent instead of innerHTML.
If your numbers might be floats you should check out parseFloat instead
If you need to be able to handle numbers like 012 you should specify the radix parameter as they might be interpreted the wrong way by parseInt.
In this case you should use parseInt(x.innerHTML,10)

it should be
var x = document.getElementById('xNum').innerHTML;
var y = document.getElementById('yNum').innerHTML;
var result = x * y;
document.write(result);

Parse them into integers:
var x = document.getElementById('xNum');
var y = document.getElementById('yNum');
var result = parseInt(x.innerHTML, 10) * parseInt(y.innerHTML, 10);

The value you are getting is a string, so in order to use it as a number you should cast it to the integer (or float):
var x = +document.getElementById('xNum').innerHTML;
var y = +document.getElementById('xNum').innerHTML;
var result = x * y;
I used unary + operator, there are another methods like parseInt, Number constructor, etc.

By now the possible ways would have been exhausted, but here's an example with textContent:
var x = document.getElementById('xNum'),
y = document.getElementById('yNum'),
toIntNum = function(element) {
return parseInt(element.textContent || element.innerText || 0, 10);
},
result;
result = toIntNum(x) * toIntNum(y);
Demo

Js:
var x = document.getByElementId('xNum').innerHTML;
var y = document.getByElementId('xNum').innerHTML;
var result = parseInt(x) * parseInt(y);
document.write(result);

you must cast as int so calculation done. By default the value consider as string .
var x = document.getByElementId('xNum');
var y = document.getByElementId('xNum');
var result = parseInt(x) * parseInt(y); //use parseInt or parseDouble
document.write(result);
and
<div id="xNum">20</div>
<div id="yNum">50</div>
it give 1000

You have to use parseInt() function in javascript for parsing a string to return an integer.
Your code should be like this :
var x = document.getElementById('xNum');
var y = document.getElementById('yNum');
var result = parseInt(x.innerHTML) * parseInt(y.innerHTML);
document.write(result);

Related

Javascript: Convert numbers inside the string

Im working on a simple conversation form, where I need to input dimensions ex. 12x24x36 inches to 304.8 x 609.6 x 914.4 mm.
My problem is I don't know how to compute convert those numbers separately.
I manage to remove the x but all the numbers merge.
Thanks, I hope you understand me.
here is my sample code
HTML
<h4>Dimensions</h4>
<label>inches <input id="number1"></label>
<label>mm <input id="number2"></label>
<button type="button" onclick="myFunction()">convert</button>
JS
function myFunction() {
var inches = document.getElementById("number1").value;
var removex = inches.replace(/x/g,"");
var input = parseInt(removex);
document.getElementById("number2").value = input
}
CODEPEN
https://codepen.io/anon/pen/yPpmej
If you have a string like:
var str = '304.8 x 609.6 x 914.4 mm'
You can use split() and parseFloat() to get an array of numbers with:
var str = '304.8 x 609.6 x 914.4 mm'
var numbers = str.split('x').map(parseFloat)
console.log(numbers)
You just need to know your input format so you can adjust for other variations.
parseFloat() will ignore any non-numeric characters after the numbers so it works well for stripping units.
If your receiving "12x24x36" as input(string) then for complete desired result update your function as below:-
function myFunction() {
var inches = document.getElementById("number1").value;
var inchesArr = inches.split("x");
var mmArr = inchesArr.map(function(i) {
return parseFloat(i) * 25.4;
});
var mmString = mmArr.join("x");
document.getElementById("number2").value = mmString;
}
EXPLANATION
You can convert your input example 12x24x36 into an array via str.split('x'), then do the math conversion from inch to millimeters (x inches * 25.4) and push those back into a new array of millimeters values. Then you can rejoin those values with an x via str.join('x') and put them back into your document. Here's what it looks like.
SCRIPT
function myFunction() {
var inches = document.getElementById("number1").value.split('x');
var millimeters = [];
for (var i = 0; i < inches.length; i++) millimeters.push(parseInt(inches[i]*25.4));
document.getElementById("number2").value = millimeters.join('x');
}
CODEPEN
https://codepen.io/anon/pen/KyZOYb

limit the query exactly with 8 and 7 digits in javascript

i have a little question:
how i can limit or generate the result of a query in 7 or 8 digits
example:
var x = 3143284294
var y = 387520525892
var z = -7632489234892
var w = 34563
result:
var x = 3143284
var y = 3875205
var z = -763248
var w = 3456300 (fill whit "0")
What function or prefix in javascript will use?
tnks(and sorry for my english)
This converts the number to a string and performs string operations on it. Note that repeat is a fairly recent feature of ECMAScript.
function cutNum(n, limit) {
n = n + '';
n = n.substr(0, limit);
if (n.length < limit) {
n = n + '0'.repeat(limit - n.length);
}
return parseInt(n, 10);
}
var x = 3143284294;
cutNum(x, 7); // 3143284
var z = -7632489234892;
cutNum(z, 7); // -763248
var w = 34563;
cutNum(w, 7); // 3456300
Take a look at the slice() method.
var numbers = "01234567890";
var res = numbers.slice(0,6);
alert(res);
Since your sample also includes that are less than 7 digits, you will want to run a logic check first prior to the slice.
var x = "01"
if(x.length < 7)
x = x + "0000000";
x = x.slice(0,6);
alert(x);

Applying math to values in an array

I have an array:
var myarray = ["5,35.0", "15,45.0", "25,45.0", "35,50.0", "45,60.0", "55,65.0", "65,60.0", "75,60.0", "85,70.0", "95,80.0"]
the values correspond to x,y points on a graph.
I need to apply math to each y value to change the y-axis scale. To keep it simple, let's say I need to multiply each y value by 2.
How would I go about this?
Use map to loop over the array, converting the string to a pair of numbers, performing the addition ensuring that the decimal place is kept intact.
var out = myarray.map(function (el) {
var xy = el.split(',').map(Number);
xy[1] = (xy[1] * 2).toFixed(1);
return xy.join(',');
});
Fiddle
You need to loop through every element and split them via ',' and then do the MATH over it and save it back.
Say,
for(var i=0;i<myarray.length;i++){
var temp = (parseFloat(myarray[i].split(',')[1])).toFixed(2);
temp = temp * 2;
myarray[i] = myarray[i].split(',')[0] + "," + temp;
}
Roughly,
var myarray = ["5,35.0", "15,45.0", "25,45.0", "35,50.0", "45,60.0", "55,65.0", "65,60.0", "75,60.0", "85,70.0", "95,80.0"];
var y = 0;
var x = 0;
for(var i in myarray) {
y = parseFloat(myarray[i].split(",")[1]);
x = parseFloat(myarray[i].split(",")[0]);
y = y * 2; // or your operation
myarray[i] = x + "," + y;
}
console.log(myarray);
HTH

JQuery multiply and add

Let's say I have some numbers that I want to multiply and add.
var a = 5;
var b = 10;
var c = 2;
var d = 3;
I want to sum b and c then multiply that by a, then add d. Easy right?
If if were a normal equation the formula would look like: (a * (b + c) + d)
But how do I do that in JQuery?
(Note: the reason for JQuery is that I'll be getting these numbers from fields and divs... and placing a total elsewhere, etc.)
By default script language does not know type as int or float. So you can fix that by multiplying 1 to the value you expect to be a number.
var a = 5;
var b = 10;
var c = 2;
var d = 3;
var total = a*1 * (b*1 + c*1) + d*1;
convert your value into float or integer first before you do calculation. Example:
var a = parseFloat($(this).val());
var b = parseInt($("#b").attr("data"));
var c = (a+10)*b;
$("#result").text(c.toFixed(2));
Just store the values in variables before you apply them to the equation:
var a = +$("#input1")[0].value;
var b = +$("#input2")[0].value;
var c = +$("#input3")[0].value;
var d = +$("#input4")[0].value;
$("#output")[0].value = a*(b+c) + d;
The plus sign before the jquery function is there to force the string value into a Number value.
Correct JQuery is 100% javascript.
Although, worth mentioning just use parseint() for the values that you get from text field
You can still do the calculation using normal javascript, just refer to the contents using jQuery selectors if necessary.

Adding two Variables together?

Trying to add two integer variables together, however, I can't seem to figure it out as it just joins them as strings?
var age_child = 10;
var age_gap = 10
alert(age_child+age_gap);
Result: 1010,
Want Result: 20
var age_child = parseInt(10);
var age_gap = parseInt(10);
alert(age_child+age_gap); // should now alert 20
To clarify, in this exact example it is not required to do parseInt. However, I assumed you didn't exactly have 10 in your code either and they're instead variables.
use
parseInt(age_child) + parseInt(age_gap);
let x = 5;
let y = 10;
let sum = x + y;
console.log('The sum of x and y is: ' + sum);

Categories