I made a simple calculator in javascript but the + button doesn't work and it just show the numbers near together
Here is my code:
<script>
function calc(operator) {
var x = document.getElementById("inp1").value;
var y = document.getElementById("inp2").value;
var z = 0;
switch (operator) {
case "+":
z = x + y;
break;
case "-":
z = x - y;
break;
case "*":
z = x * y;
break;
case "/":
z = x / y;
break;
}
document.getElementById("result").innerHTML=z;
}
</script>
You may use like this:
z= +x + +y; // + is prefixed to convert input into number
The x and y variables contain strings. Parse them to numbers:
var x = parseFloat(document.getElementById("inp1").value);
var y = parseFloat(document.getElementById("inp2").value);
It happens to work for the other operators, because there are no subtraction, multiplication or division for strings, it figures out that it has to convert the strings to numbers.
var x=document.getElementById("inp1").value;
var y=document.getElementById("inp2").value;
return you values in those text boxes as strings.
When you use + operator on strings, it will concatenate the values. If you use the same operator on numbers, it will add the values.
You will need to parse the text box values into integer using the parseInt function using one of the following ways.
var x=parseInt(document.getElementById("inp1").value);
var y=parseInt(document.getElementById("inp2").value);
and then do z=x+y; I would recommend this because all the operations, not just addition, will be perfomed on the integers.
or simply change z=z+y; to look like z = parseInt(x) + parseInt(y);
A quick way to convert a string to a number is to use the unary + operator.
z = +x + +y
or
z = parseInt(x) + parseInt(y);
var x = parseInt(document.getElementById("inp1").value);
this converts your "string" number to integer, also you can use parseFloat() if you have float numbers
You may use like this:
var x = document.getElementById("inp1").value*1;
var y = document.getElementById("inp2").value*1;
x in this moment is number!!
More clean for me!!!
Related
What is wrong with my code?? Everything except the subtraction works. It just returns NaN. I am new to javascript so i might have written my code poorly.
// Variables
var count = prompt("Choose an arithmetic method: \n1. Addition \n2. Subtraktion\n3. Multiplikation\n4. Division");
var x = parseInt(prompt("Enter your first number", "0"));
var y = parseInt(prompt("Enter your second number", "0"));
var z = +x + +y;
// Switch function with 4 cases
switch(count) {
case '1':
alert("Answer: " + z);
break;
case '2':
alert("Answer: " + x - y);
break;
case '3':
alert("Answer: " + x * y);
break;
case '4':
alert("Answer: " + x / y);
break;
}
You need to group the operations in parentheses, for instance alert("Answer: " + (x - y)); (and the same for the others). Otherwise JavaScript runs "Answer: " + x first, resulting in a string.
Also, always specify the radix (you want 10) for parseInt: parseInt(input, 10), otherwise some engines get confused with octal numbers.
Your trouble is here:
alert("Answer: " + x - y);
Due to how the association of operators work, it works as if you had written this:
alert(("Answer: " + x) - y);
You need to write it like this:
alert("Answer: " + (x - y));
Snippet here:
// Variables
var count = prompt("Choose an arithmetic method: \n1. Addition \n2. Subtraktion\n3. Multiplikation\n4. Division");
var x = parseInt(prompt("Enter your first number", "0"));
var y = parseInt(prompt("Enter your second number", "0"));
var z = +x + +y;
// Switch function with 4 cases
switch (count) {
case '1':
alert("Answer: " + z);
break;
case '2':
alert("Answer: " + (x - y));
break;
case '3':
alert("Answer: " + x * y);
break;
case '4':
alert("Answer: " + x / y);
break;
}
Wrap your subtraction in parentheses: (x - y). You would get an unexpected result from the addition, too, if you put x + y there instead of z.
What's happening is operator precedence. Multiplication and division are higher precedence than addition, so they get done first - before the implicit conversion to string for concatenation.
With subtraction, '+' and '-' are equal in precedence and so get done in order from left to right. So the concat takes place before the math, which leaves you attempting to subtract y from a string (which doesn't work, and so...NaN).
With addition, it would simply concatenate the two numbers onto the string.
I am writing a Javascript function where strings with apostrophe ( ' ) are not being displayed. Is there a way I can go around this? The below function assumes x is a string.
function addItem(x, y) //adds item on screen and adds Total
{
var newRow = "<tr><td>"+x+"</td><td>€"+y.toFixed(2)+"</td><td><input type=\"button\" onclick=\"subtract("+y+")\" value = \"X\"></td></tr>"
$('#order').append(newRow);
document.getElementById("currentorder").value += newRow;
//Adds Total Value
var total = document.getElementById('price').innerHTML;
total = parseFloat(total);
var z = +y + +total;
document.getElementById('price').innerHTML=z.toFixed(2);
event.preventDefault();
}
Confusing Addition Operators
The following line looks quite a bit off :
var z = +y + +total;
If you just want to add y and total, just simplify it as :
var z = y + total;
Consider Possible Parsing Errors
Another idea would be to consider stripping out any non float related characters (i.e. non decimals and digits) within your string prior to calling your parseFloat() function :
var total = parseFloat(document.getElementById('price').innerHTML.replace(/[^\d\.]/g,''));
This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 9 years ago.
I was trying to do some simple mathematical calculations in HTML and jQuery and JavaScript, so I wanted to get input from user.
For input I tried doing this :
var x = prompt("Enter a Value","0");
var y = prompt("Enter a Value", "0");
But I am not able to perform any kind of calculations as these values are strings.
Please, can any one show me how to convert them into integers.
parseInt() or parseFloat() are functions in JavaScript which can help you convert the values into integers or floats respectively.
Syntax:
parseInt(string, radix);
parseFloat(string);
string: the string expression to be parsed as a number.
radix: (optional, but highly encouraged) the base of the numeral system to be used - a number between 2 and 36.
Example:
var x = prompt("Enter a Value", "0");
var y = prompt("Enter a Value", "0");
var num1 = parseInt(x);
var num2 = parseInt(y);
After this you can perform which ever calculations you want on them.
JavaScript will "convert" numeric string to integer, if you perform calculations on it (as JS is weakly typed). But you can convert it yourself using parseInt or parseFloat.
Just remember to put radix in parseInt!
In case of integer inputs:
var x = parseInt(prompt("Enter a Value", "0"), 10);
var y = parseInt(prompt("Enter a Value", "0"), 10);
In case of float:
var x = parseFloat(prompt("Enter a Value", "0"));
var y = parseFloat(prompt("Enter a Value", "0"));
var xInt = parseInt(x)
This will return either the integer value, or NaN.
Read more about parseInt here.
You can use parseInt() but, as mentioned, the radix (base) should be specified:
x = parseInt(x, 10);
y = parseInt(y, 10);
10 means a base-10 number.
See this link for an explanation of why the radix is necessary.
Working Demo Reading more Info
parseInt(x) it will cast it into integer
x = parseInt(x);
x = parseInt(x,10); //the radix is 10 (decimal)
parseFloat(x) it will cast it into float
Working Demo Reading more Info
x = parseFloat(x);
you can directly use prompt
var x = parseInt(prompt("Enter a Number", "1"), 10)
You have to use parseInt() to convert
For eg.
var z = parseInt(x) + parseInt(y);
use parseFloat() if you want to handle float value.
Using the following code I want to move a line with id='seekline' by var1 (less than .1 in most cases), but I run into trouble adding var1 and j.
The plus sign concatenates instead of adding. I have tried using Number(), parseInt(), parseFloat(), and forcing addition by multiplying by 1 or adding by 0. For some reason I cannot stop the concatenation. When I use parseInt() or parseFloat() (e.g. parseInt(j,10)) the code stops working.
The string split is to remove the px from element.style.left.
function move(var1) {
element = document.getElementById('seekline');
console.log(var1, element.style.left);
var str=(element.style.left);
var n=str.split("p");
var j = n[0];
Number(j);
Number(var1);
var k = var1 + j;
var f = k.concat("px");
console.log(j, k, f);
element.style.left = f;
}
You need to assign the result of the call to Number(), as it returns the numeric value of the string passed instead of modifying the variable itself.
Note that +foo is the same as doing Number(foo).
function move(var1) {
var style = document.getElementById('seekline').style;
// removes last two 'px' characters
var oldValue = +style.left.slice(0, -2);
// converts to number type, then adds 2 to it
var1 = +var1;
var1 += 2;
// check to see if number is NaN or +/-Infinity
if (isFinite(var1)) {
// only now string concatenates the term 'px' to it
element.style.left = oldValue + var1 + 'px';
}
}
function move(var1) {
var element = document.getElementById('seekline'),
left = parseInt(element.style.left.replace('px',''),10);
element.style.left = ((left++) + var1) + 'px';
}
The secret for you to work with numbers obtained from JavaScript, is to remove the string 'px' and convert them to numbers:
parseInt(element.style.left.replace('px', ''))
This is my function:
var ans=(X*X)/(Y+Z);
When I enter 10, 20, and 10 - respectively- the addition bit comes out as 2010 and not 30.
How can I fix this?
Make sure to convert your strings to numbers first:
var X = "10";
var Y = "20";
var Z = "10";
X = +X; // unary plus operator converts to a number
Y = Number(Y); // or use the Number function
Z = parseInt(Z, 10); // or parseInt
var ans=(X*X)/(Y+Z);