Output come as string [duplicate] - javascript

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I just want to add two numbers in javascript using prompt but the output comes as a string.
var num1 =prompt("enter a number");
var num2=prompt("enter a number");
var sum =num1+num2;
console.log(`the of ${num1} and ${num2} ${sum} `);

The return type of prompt is string so it is needed to convert string to number to do sum operation.
var num1 = Number(prompt("enter a number"));
var num2 = Number(prompt("enter a number"));
var sum =num1 + num2;
console.log(`the of ${num1} and ${num2} ${sum} `);

Related

Adding prompts to an array in javascript [duplicate]

This question already has answers here:
How to save prompt input into array
(5 answers)
Closed 7 months ago.
I'm busy with a task that requires me to ask the user to keep entering random numbers until the number is "-1". After that I would have to get the average of all the numbers entered excluding the "-1". I've gotten this far with it:
var userNumbers;
while (userNumbers !== "-1") {
userNumbers = prompt("Enter a number");
}
numbersArray = [userNumbers];
console.log(numbersArray);
Try this
// Store all numbers
const numbers = [];
let userNumber;
for(;;){
userNumber = prompt("Enter a number");
if(userNumber === '-1') { break; }
numbers.push(userNumber);
}
// Calculate average
let sum = 0;
let avg = 0;
numbers.forEach((value) => sum += value);
avg = sum / numbers.length

Javascript + sign is concatenates instead of giving sum of variables [duplicate]

This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 1 year ago.
if x,y,z are all 1 its giving the answer 111 rather than 3
x=prompt ("Enter first Number");
y=prompt ("Enter second Number");
z=prompt ("Enter third Number");
p= x + y + z ;
You could use something like this
x = parseInt(prompt("Enter first Number"), 10);
y = parseInt(prompt("Enter second Number"), 10);
z = parseInt(prompt("Enter third Number"), 10);
p = x + y + z;
console.log(p)

Save and parseInt user input in one line of code? (Javascript) [duplicate]

This question already has answers here:
Why is parseInt() not working? [duplicate]
(4 answers)
Closed 3 years ago.
Here's my code:
function add() {
var num1 = prompt("Enter 1st number")
var num2 = prompt("Enter 2nd number")
parseInt(num1);
parseInt(num2);
var result = num1 + num2;
alert(result);
}
add();
I'm trying to build a simple addition calculator. parseInt wasn't working and an answer here said to declare the variable like var num1 = parseInt(num1);. However since I'm only getting "num1" through user input (var num1 = prompt..."), not sure how to store it as integer, or parseInt, in the same line. Any advice? Thanks.
All you have here are standalone, unused expressions:
parseInt(num1);
parseInt(num2);
Those evaluate to numbers, but you don't use them, so they're useless. Either assign them to variables, eg
const actualNum1 = parseInt(num1);
const actualNum2 = parseInt(num2);
and then use those variables, or just wrap the prompt in parseInt:
var num1 = parseInt(prompt("Enter 1st number"))
var num2 = parseInt(prompt("Enter 2nd number"))
Unless you're intending to only accept integers, consider using Number instead:
var num1 = Number(prompt("Enter 1st number"))
var num2 = Number(prompt("Enter 2nd number"))

Prompts when numbers are added together it just puts the number and the other number together [duplicate]

This question already has answers here:
Sum of two numbers with prompt
(10 answers)
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 4 years ago.
I am working on a geometry style like calculator using javascript, and I need user input. But when the user, for example, inputs 55 and the other also 55 the sum of the number will be 5555 when I'd like it to be 110.
Javascript Code:
function ftmad2(){
let angle1 = prompt("Please enter the first angle:");
let angle2 = prompt("Please enter the second angle:");
sumAngle = angle1 + angle2;
console.log(sumAngle);
let result = 180-sumAngle;
document.getElementById("result").innerHTML = result;
}
Common issue; it is reading 55 as a string, rather than a number, do:
sumAngle = parseInt(angle1, 10) + parseInt(angle2, 10);
Current senerio
"55"+"55" //which will return 5555 obviously
Use parseInt to convert string to int because your both value angle1 and angle2 coming in string format, you should convert into int before sum.
required senerio
55 + 55 //which will return 110
function ftmad2(){
let angle1 = prompt("Please enter the first angle:");
let angle2 = prompt("Please enter the second angle:");
angle1 = parseInt(angle1);
angle2 = parseInt(angle2);
sumAngle = angle1 + angle2;
console.log(sumAngle);
let result = 180-sumAngle;
document.getElementById("result").innerHTML = result;
}
ftmad2();
<p id="result"></p>
prompt() returns a string.
When you do angle1 + angle2 you're joining two strings instead of summing two numbers.
In order for this to work, you'll have to transform the strings in numbers first. Like this:
function ftmad2(){
let angle1 = prompt("Please enter the first angle:");
let angle2 = prompt("Please enter the second angle:");
sumAngle = parseFloat(angle1) + parseFloat(angle2);
console.log(sumAngle);
let result = 180-sumAngle;
document.getElementById("result").innerHTML = result;
}
ftmad2();
<div id="result"></div>

Unexpected output in javascript

I am beginner to javascript and i am getting unexpected output
here is the code
<script type="text/javascript">
function add(a,b)
{
x = a+b;
return x;
}
var num1 = prompt("what is your no.");
var num2 = prompt("what is another no.")
alert(add(num1,num2));
</script>
it should give output as a sum of two number entered by us on prompting but it is simply concatenating the two number and popping the output
This is because the prompt function returns a String and not a Number. So what you're actually doing is to request 2 strings and then concatenate them. If you want to add the two numbers together you'll have to convert the strings to numbers:
var num1 = parseFloat(prompt("what is your no."));
var num2 = parseFloat(prompt("what is another no."));
or simpler:
var num1 = +prompt("what is your no.");
var num2 = +prompt("what is another no.");
prompt returns a string, not a number. + is used as both an addition and concatenation operator. Use parseInt to turn strings into numbers using a specified radix (number base), or parseFloat if they're meant to have a fractional part (parseFloat works only in decimal). E.g.:
var num1 = parseInt(prompt("what is your no."), 10);
// radix -----^
or
var num1 = parseFloat(prompt("what is your no."));
When you prompt the user, the return value is a string, normal text.
You should convert the strings in numbers:
alert(add(parseInt(num1), parseInt(num2));
The return value of prompt is a string. So your add function performs the + operator on 2 strings, thus concatenating them. Convert your inputs to int first to have the correct result.
function add(a,b)
{
x = parseInt( a ) + parseInt( b );
return x;
}
In addition to the already provided answers: If you're using parseInt() / parseFloat(), make sure to check if the input in fact was a valid integer or float:
function promptForFloat(caption) {
while (true) {
var f = parseFloat(prompt(caption));
if (isNaN(f)) {
alert('Please insert a valid number!');
} else {
return f;
}
}
}
var num1 = promptForFloat('what is your no.');
// ...

Categories