I have written code to calculate the values like integer values.
function add_number(inp) {
var tr = inp.parentNode.parentNode;
var first_number = parseInt(tr.querySelector('[data-id="qty"]').value);
var second_number = parseInt(tr.querySelector('[data-id="amtper"]').value);
var result = first_number * second_number;
tr.querySelector('[data-id="total"]').value = result ? result : '';
}
By the above code U am able to calculate only round values, if I calculate the values 10.60*10 = 106, (the value should be displayed). But I am getting 100.
How to calculate point values?
if I calculate the values 10.60*10 = 106, (the value should be
displayed). But I am getting 100
Because when you do parseInt, it returns an Intger without any decimal value.
Use parseFloat instead, Replace
var first_number = parseInt(tr.querySelector('[data-id="qty"]').value);
var second_number = parseInt(tr.querySelector('[data-id="amtper"]').value);
with
var first_number = parseFloat(tr.querySelector('[data-id="qty"]').value);
var second_number = parseFloat(tr.querySelector('[data-id="amtper"]').value);
parseInt() parses only integer values without decimal value.
Use parseFloat() instead.
var first_number = parseFloat(tr.querySelector('[data-id="qty"]').value);
var second_number = parseFloat(tr.querySelector('[data-id="amtper"]').value);
Use parseFloat? See this:
function add_number(inp) {
var tr = inp.parentNode.parentNode;
var first_number = parseFloat(tr.querySelector('[data-id="qty"]').value);
var second_number = parseFloat(tr.querySelector('[data-id="amtper"]').value);
var result = first_number * second_number;
tr.querySelector('[data-id="total"]').value = result ? result : '';
}
add_number(document.getElementById("inp"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
QTY: <input data-id="qty" value="100"><br>
AMTPER: <input data-id="amtper" value="1.06">
<div>
<div id="inp"></div>
</div>
<hr>
Total, filled by JS:
<input data-id="total">
</div>
parseInt will convert 10.60 to 10 before the multiplication. You need to use parseFloat instead. In case you expect an integer or a number with fixed number digits after the decimal point, you can use the precision parameter to set it.
function add_number(inp, precision) {
precision = typeof precision !== "number"? 0: precision;
var tr = inp.parentNode.parentNode;
var first_number = parseFloat(tr.querySelector('[data-id="qty"]').value);
var second_number = parseFloat(tr.querySelector('[data-id="amtper"]').value);
var result = (first_number * second_number).toFixed(precision);
tr.querySelector('[data-id="total"]').value = result ? result : '';
}
Related
var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
var val = binaryValue.value;
var result = 0;
var i = val.length-1;
var j = 0;
while (i > -1) {
var y = (Number(val[i])) * (2 ** [j]);
result += y;
i--;
j++;
console.log(y);
}
decimalValue.value = result;
console.log(binaryValue.value);
}
Using the code above, I tried to obtain a value from an input field and do a calculation to convert it to a decimal number. But it doesn't obtain the input value. I tried several times and I am unable to figure out it.
This is how you get a value from an input field:
var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
var NumValue = binaryValue.value
console.log("input value: " + NumValue);
//this is how you convert a binary number to decimal
console.log("binary number: " + (NumValue >>> 0).toString(2));
//this is how you convert an decimal number to binary
console.log("decimal number: " + parseInt(NumValue, 2));
}
<input type="text" id="binary" placeholder="insert value"/>
<button type="button" onclick="binaryToDecimal()">Show value</button>
Use this example to fix your code.
I also added ways to convert to and from binary numbers.
I have some problem with my js code which when I run the code it show me a NaN error, I have a function that calculate something.
Example:
<p id = "total "></p>
total = num1 *num2;
document.getElementById("total").innerHTML = total;
And it works fine but when I create a new function to calculate the discount
var price = document.getElementById("total").value;
discount = total *0.10;
It shows a NaN, I tried a lot of solution but it is still not working.
Can you help me?
I think you have a concept mistake, if the value is a HTML value, i mean, is inside of
<p id="this_is_the_element">123456789</p>
You can get that value with javascript using the
var number = document.getElementById('this_is_the_element').innerHTML
now the number variable will have inside "123456789" as a STRING
But if you are using an input you should use
var number = document.getElementById('this_is_the_element').value
Now, try this. First try to avoid the parseInt, instead use Number.
Define a function
var discount = function(){
var price = Number(document.getElementById("total").innerHTML);
return price*0.1;
}
If you want to do it on new sintax use this
const discount = () => {
const price = Number(document.getElementById("total").value);
return price*0.1;
}
There are few issues in your code:
There is no value property of p element. To access the text in p element, you can use either textContent or innerText.
By default the text is of type string. Multiplying string with number gives you NaN. You have to convert that to number before doing any arithmetic operation.
var num1 = 5;
var num2 = 20;
var total = num1 *num2;
document.getElementById("total").textContent = total;
var elTotal = Number(document.getElementById("total").textContent);
var discount = elTotal * 0.10;
console.log(discount)
<p id = "total"></p>
When you pull the value, it's a String, and JavaScript for the most part will automatically do type conversion, but you can always wrap it in parseInt to force it to be a Number.
discount = parseInt(total) * 0.10;
You can also always run typeof total to verify if total is a Number or String, and you can run console.log(total) to visually verify the contents.
Also, your document.getElementById("total") references a paragraph element, which doesn't have .value property, so you should use innerText to get its value instead.
Demo
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
button1.addEventListener('click', function() {
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
total = parseInt(num1) * parseInt(num2);
document.getElementById("total").innerText = total;
});
button2.addEventListener('click', function() {
var total = document.getElementById("total").innerText;
discount = parseInt(total) * 0.10;
document.getElementById('discount').innerText = discount;
});
<input type="text" id="num1" /><br>
<input type="text" id="num2" /><br>
<button id="button1">Add</button>
<p id="total"></p>
<button id="button2">Discount</button>
<p id="discount"></p>
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
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
I've used var.split("_"); here. Example of a value I'm trying to get would be: 2_25000
However, below code results a NaN value.
function calculateTotal() {
var room_type_id = document.getElementById('room_type_id').value;
var room_type_cost = room_type_id.split("_");
var meal_type_id = document.getElementById('meal_type_id').value;
var meal_type_cost = meal_type_id.split("_");
var bed_type_id = document.getElementById('bed_type_id').value;
var bed_type_cost = bed_type_id.split("_");
var ext_beds_id = document.getElementById('ext_beds_id').value;
var reservation_duration = document.getElementById('reservation_duration').value;
document.getElementById('total_amount').value = ( Number(room_type_cost[1]) + Number(meal_type_cost[1]) + Number(bed_type_cost[1]) + Number(ext_beds_id) ) * Number(reservation_duration);
}
you may use number() function or parseInt() function but remember to also pass the base 10 second parameter in parseInt("23", 10), also you can prefix + symbol to convert it to integer.
for i.e., +"23" + 2
Try this one............
change
Number()
to
parseInt()
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);