This question already has answers here:
Plus Arithmetic Operation
(7 answers)
Closed 8 years ago.
I am trying to add up the 2 values (bold) that are inputed by the user but instead of adding then mathematically (100+1 = 101) it adds them like this (100+1 = 1001).
$('#inputcost').keyup(function(){
var price = $(this).val();
});
function checkboxcost() {
var sum = 0;
var gn, elem;
for (i=0; i<2; i++) {
gn = 'extra'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value); }
}
**var total = (price.value + sum.toFixed(2));
document.getElementById('totalcost').value = "$" + total;**
}
</script>
<input id="totalcost" disabled/>
The problem is, as you suspect, in this line:
var total = (price.value + sum.toFixed(2));
The problem is that .toFixed converts the number to a string for display. So you are trying to add a string to a number, which results in concatenation, not addition.
You want to add the numbers together, then display the sum:
var total = (price.value + sum).toFixed(2);
With that said, I'm not sure where price.value is coming from, so it's possible that's a string too. In which case, convert it with the unary plus + operator:
var total = (+price.value + sum).toFixed(2);
Its treating price.value as String so convert that string to number like:
var total = (Number(price.value) + sum.toFixed(2));
it seems string addition is taking place.
So try converting string numbers to integer using parseInt() like:
var x = parseInt("1")
var y = parseInt("2")
var z = x + y
Try parseInt(price.value) + ...
It's because the types of the operands are strings and the + operator for two strings does concatenation, not addition.
If you convert them to numbers then you'll get a number result:
"1" + "2" == "12"
parseFloat("1") + parseFloat("2") == 3
Related
This question already has answers here:
How to compute the sum and average of elements in an array? [duplicate]
(35 answers)
Closed 10 months ago.
I tried to iterate through the array and print the sum. But the output am getting is elements of the array.
<p id="ans"></p>
<script>
var text = "the mean is ";
function mean() {
var sum = 0;
var input = document.getElementsByName("values");
for (var i = 0; i < input.length; i++) {
sum += input[i].value;
text = text + sum;
}
document.getElementById("ans").innerHTML = text;
}
</script>
Parse the string values into integers and then sum it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
This is because in javascript if you adding a number to a string it will be casted to a string. For example:
0 + '1' + '2' // 012
But with parse int:
0 + parseInt('1') + parseInt('2') // 3
Or you can cast to int with a simple plus also:
0 + (+'1') + (+'2') // 3
I want to make an easy website because I want to learn javascript. The website will have just one (number) input named "number". After clicking on submit button the website will convert the number from decimal to binary system and show the answer.
This is the javascript part that should convert the number and show the answer in a div with ID = result:
var selectedNumber = document.getElementByName("number").value;
var k = [];
var a = 0;
var b = 1;
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k=k.append(a);
selectedNumber = Math.floor(selectedNumber/2);
}
else{
k=k.append(b);
selectedNumber = Math.floor(selectedNumber/2);
}
}
k=k.append(b);
for i in reversed(k){
document.getElementById("result").innerHETML = i;
}
Unfortunately, I don't have much experience using javascript and this code doesn't work. I've made a similar program in python and based this code on that in python.
Here's the corrected code:
Tip - Whenever you have to glue two numbers to form a string make sure to do 1 + "" +2
var selectedNumber = 105;//document.getElementByName("number").value;
var k = [];
var a = 0;
var b = 1;
var output = '';
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k=k+""+a;
selectedNumber = Math.floor(selectedNumber/2);
}
else{
k=k+""+b;
selectedNumber = Math.floor(selectedNumber/2);
}
}
k=k+""+b;
console.log(k);
//document.getElementByName("number").value = k;
Simplest way is to use toString(2) method.
let a =7
console.log(a.toString(2))
I have made some minor changes to your code. removed redundant lines. i am appending values to a front of string instead of an array ( which you later reverse and join).
function handle(){
let selectedNumber = document.getElementById("number").value;
let k = '',a = 0, b = 1;
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k= a+k
}
else{
k=b+k
}
selectedNumber = Math.floor(selectedNumber/2);
}
k=b+k;
document.getElementById("result").innerHTML = k;
}
#result{
color: green;
font-size:25px;
}
<input id='number' placeholder='enter value'></input>
<button onClick=handle()>Convert to binary</button>
<div id='result'></div>
It's a whole lot simpler than that. The .toString() method takes an optional argument that can be used to convert a number to a different numerical base system, like its binary, octal or hex values.
Prepending the input's value with +, forces the input's value to become a number.
document.querySelector("button").addEventListener("click", function(){
let number = +document.querySelector("input").value; // Convert input into a string
console.clear();
console.log("The decimal: " + number + " converted to a binary is: " + number.toString(2));
console.log("The decimal: " + number + " converted to an octal is: " + number.toString(8));
console.log("The decimal: " + number + " converted to a hex is: " + number.toString(16));
});
<input><button>Convert!</button>
For this goal, actually you can forget all your code and simple use Number.prototype.toString(). It takes an optional argument of the base you want to use for convert the number to string.
Example:
const convert = () =>
{
let number = document.getElementById("iNumber").value;
binNumber = Number.parseInt(number, 10).toString(2);
document.getElementById("dRes").innerHTML = binNumber;
};
<input id="iNumber" type="number">
<button id="btnToBinary" onclick="convert()">
Convert To Binary
</button>
<div id="dRes"></div>
I'm trying to make operations with numbers that are stored in arrays, unfortunately they seem to be considered as "text" rather than numbers, so when I do like array1[i] + array2[i], instead of doing 2+3=5 I would get 2+3=23 ...
The values of these arrays come from fields (html)
No idea how to deal with that ;D
Thanks for your help
If you wanna look at my code, here's what it looks like :
var polynome = [];
for (var i=0; i<=degree; ++i) {
polynome[i] = document.getElementById(i).value;
}
var a = document.getElementById("a").value;
var tempArray = [];
var quotient = [];
quotient[degree+1] = 0;
for (var i=degree; i>=0; --i) {
tempArray[i] = a * quotient[i+1];
quotient[i] = polynome[i] + tempArray[i];
}
document.getElementById("result").innerHTML = polynome + "<br>" + tempArray + "<br>" + quotient;
array1[i] contains string and not int so when you are trying both elements with + operator it is concatenating both the values rather of adding them
you need to cast both elements in arrays to integer
try this
parseInt( array1[i] ) + parseInt( array2[i] )
The + punctuator is overloaded an can mean addition, concatenation and conversion to number. To ensure it's interpreted as addition, the operands must be numbers. There are a number of methods to convert strings to numbers, so given:
var a = '2';
var b = '3';
the unary + operator will convert integers and floats, but it's a bit obscure:
+a + +b
parseInt will convert to integers:
parseInt(a, 10) + parseInt(b, 10);
parseFloat will convert integers and floats:
parseFloat(a) + parseFloat(b);
The Number constructor called as a function will convert integers and floats and is semantic:
Number(a) + Number(b);
Finally there is the unary - operator, but it's rarely used since subtraction (like multiplication and division) converts the operands to numbers anyway and it reverses the sign, so to add do:
a - -b
I have this code that add numbers and prints it in input text for readonly
document.getElementById('total') += parseInt(tot);
but it JUST adds numbers as sting , for example when add 8 and 10 that would be 18 but it prints them as 810 , why ?
Use the parseInt() function to both of them:
document.getElementById('total').value = parseInt(tot)+parteInt(document.getElementById('total').value);
Just parse the value from string to integer like this
var x = document.getElementById('total');
x.value = parseInt(x.value) + parseInt(tot);
Or use parseFloat() if you have decimal numbers.
You can try this:
var elem = document.getElementById('total');
elem.value = +elem.value + parseInt(tot);
The + sign force the type to number.
I have the following piece of code:
if(netAnnualBilling == null){
netAnnualBilling = 0;
parseFloat(netAnnualBilling);
}
parseFloat(netAnnualBilling);
annualBillingCount = (annualBillingCount + netAnnualBilling);
parseFloat(annualBillingCount);
My two variables netAnnualBilling and annualBillingCount are both of type numbers. However, when I get to this line:
annualBillingCount = (annualBillingCount + netAnnualBilling);
javascript seems to turn annualBillingCount into type String and appends the two numbers together instead of adding or subtracting as its supposed to. Example:
annualBillingCount = 0;
netAnnualBilling = -1403.30
The result of the above code will show annualBillingCount to be equal to : 0-1403.80
I've tried ParseFloat every time these variables pop up but I'm not having any luck. What's going on?
If you want to make sure the variables are used as numbers, you can simply prepend the unary plus operator:
annualBillingCount = +annualBillingCount + +netAnnualBilling;
will force each operand to be treated as a number.
EDIT Heres a basic fiddle showing the addition of two strings with varying uses of the unary casting, using the code below:
var onetwo = "12";
var threefour = "34";
alert(onetwo + threefour); // string + string, so "12" + "34" = "1234"
alert(+onetwo + threefour); // number + string, so 12 + "34" = "12" + "34" = "1234"
alert(onetwo + +threefour); // string + number, second will be coerced back to string, so "12" + "34" = "1234"
alert(+onetwo + +threefour); // number + number, so 12 + 34 = 46
parseFloat() doesn't change the value, it returns the casted value. You need:
netAnnualBilling = parseFloat(netAnnualBilling)
Try this:
if(netAnnualBilling == null) {
netAnnualBilling = 0;
}
netAnnualBilling = parseFloat(netAnnualBilling);
annualBillingCount = parseFloat(annualBillingCount);
annualBillingCount += netAnnualBilling;