I am a beginner in JavaScript. Our teacher asked us to write a program to add two numbers using function add(). The question is shown as follows.
However, when I use my code to add the two numbers. The result is not a number.
<html>
<head> <title> Third example </title>
<script type="text/javascript">
function sum (x,y)
{ num1=parseInt(x);
num2=parseInt(y);
return (num1+num2);}
var input1 = window.prompt("Enter a number: ", 0);
var input2 = window.prompt("Enter another number: ", 0);
var input3 = window.prompt("Enter another number: ", 0);
var value1 = parseFloat(input1 + input2);
var value3 = parseFloat(input3);
var sum = sum(value1 + value3);
document.writeln("<h1> First number: " + value1 + "</h1>");
document.writeln("<h1> Second number: " + value3 + "</h1>");
document.writeln("<h1> Sum: " + sum + "</h1>");
</script>
<head>
<body></body> </html>
Why the sum is not a number?
You have to add parseFloat() separately for input1 and input2 when you calculate the sum for value1. Another change is the var sum = sum1(value1 , value3); instead of var sum = sum1(value1 + value3); which makes the parameter y of sum(x,y) as undefined.
var input1 = window.prompt("Enter a number: ", 0);
var input2 = window.prompt("Enter another number: ", 0);
var input3 = window.prompt("Enter another number: ", 0);
var value1 = parseFloat(input1) + parseFloat(input2);
var value3 = parseFloat(input3);
var sum = sum1(value1 , value3);
document.writeln("<h1> First number: " + value1 + "</h1>");
document.writeln("<h1> Second number: " + value3 + "</h1>");
document.writeln("<h1> Sum: " + sum + "</h1>");
function sum1 (x,y)
{
return (x+y);
}
Also, as Adriani6 mentioned you don't need to parseFloat again inside sum1 as you assign a parsed float already to value1 and value3
Although a bit dirty, this works:
var amount = 58.02;
var total = '£' + (amount*1 + 177);
...gives the the expected answer of £217.73
Enclosing within brackets forces 'amount' to be a number. However...
var amount = 40.73;
var total = '£' + (amount*1 + 177.82);
gives a really silly answer of £218.54999999999998 (!)
[ Edited 26th January - following part in italics kept for reference...
This is only true if the (correct) decimal part of the answer is .55 or .65 Bug in Javascript???? (It's the same in Firefox and Chrome.)
So some more manipulation is required to be absolutely certain: multiplication, integerising and subsequent division by 100...
var amount = 40.73;
document.write('Total is: £' + parseInt(amount*100 + 17782) / 100);
.. gives the correct answer of 'Total is: £218.55' ]
Edit: Better solution found later uses toFixed() :-
var amount = 40.73;
var total = 'Total is: £' + (amount* + 177.82).toFixed(2);
.. also gives the correct answer of 'Total is: £218.55'
Soooooo -
1) You need to enclose the numbers you want to add within brackets if the sum will be part of a string;
2) Multiplying each 'number' by one forces the result to be a number - so (input1*1 + input2*1) is forced to be the arithmetic sum. This is necessary in the original questioner's script, but multiplying by one isn't needed in my example;
3) To ensure you don't get a silly answer, append .toFixed(n) to the bracketed expression - where n is the number of decimal places.
Utterly tedious (still)....
(and) Much better to use PHP if you can!
The error you're seeing is here:
sum(value1 + value3)
Your sum function expects the arguments separately and will internally perform the addition, but you're adding them in-line before sending them to the function. Since only one value is sent to sum(), its second argument is undefined and therefore "not a number". Simply separate the values:
sum(value1, value3)
The other error that you may not have noticed yet is here:
parseFloat(input1 + input2)
If you enter 1 and 2 for example, the result of this will be 12. This is because you're "adding" (concatenating) the strings before converting them to a numeric value. Convert them first, then add them. Something like this:
var value1 = parseFloat(input1) + parseFloat(input2);
Aside from that the code can probably be cleaned up a bit more, such as not needing all of the parsing you're doing. (Once something is parsed to a numeric value, it doesn't need to be parsed to a numeric value again.) You'd also do well to look into setting values to elements on the page instead of using things like document.writeln(), but that could be a lesson for another day.
Because in Javascript, the + operator is overloaded, i.e., has multiple meanings depending on the arguments you give it. The + means concatenation for strings and addition for "numbers" (for different types of numbers).
You can use an add function that takes and ads as many parameters as you need:
function add() {
// Create an array from the functions arguments object
// then sum the array members using reduce
var sum = Array.from(arguments).reduce(function(a, b) {
return a + b;
});
console.log(sum);
}
// You can now add as many numbers as you like
// just by passing them to the function
add(2, 5);
add(2, 3, 5);
Related
I have just started learning Javascript. I am doing the course in Viope World. I need to get two different numbers, but each time, I get the same number for the num and exponent variables, while the function calcPower is correct. I don't understand how to get different inputs in the function fetchValue() without having HTML for this task. I have tried using the method Document.querySelector() and other things which shouldn't be complicated for such an exercise.
These are the requirements:
Fill in the missing functions fetchValue(id) and calcPower(base, exponent). The function fetchValue(id) looks for a HTML text input element and returns its value. The function calcPower(base, exponent) has to calculate and return a number based on the values passed to it. Note that all of the printing happens within the pre-made section of the program.
This is the part of the code I can't change:
function calcFunc(){
var num = fetchValue("num");
var exponent = fetchValue("exponent");
console.log("The number " + num + "to the power of " + exponent + " is:");
console.log(calcPower(num, exponent));
}
My code:
function fetchValue(id){
let val = document.querySelector("input").value;
return val;
}
function calcPower(base, exponent){
var result = 1;
for(var counter=0; counter<exponent;counter++){
result*=base;
}
return result;
}
querySelector returns a reference to the first element of the given selector. See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector. It is not the obvious way to fetch your values given that your function is set up to handle element ids.
Instead, individual elements with unique id can be referenced using document.getElementById("elementID") and you want the .value property of the element. See https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById.
To input values, the html needs some sort of input, you could use text or number inputs (both return strings, but the number input restricts entries to digits). The markup for these would be something like:
Number: <input type="number" id="inputValue"></input><br>
Exponent: <input type="number" id="inputExponent"></input>
Note the use of ids as attributes of the elements.
Javascript is a loosely typed language, meaning strict definition of variable types is not needed. This means that JS can make sensible calculations from 2*2 or "2"*"2" (both are calculated to be 4). However, it is good practice to formally convert string digits to numbers when you intend using them for calculations (not least because JS interprets "2"+"2" as "22" because + is both an arithmetic addition operator and a string concatenation operator so if you give it strings, JS assumes you want to concatenate them).
So, the fetchValue function could include the use of parseInt(string) to convert the input string values to numbers.
These principles are combined in the following working snippet to illustrate the approach:
function calcFunc(){
let num = fetchValue("inputValue");
let exponent = fetchValue("inputExponent");
console.log("The number " + num + " to the power of " + exponent + " is:");
console.log(calcPower(num, exponent));
}
function fetchValue(id){
return parseInt(document.getElementById(id).value);
}
function calcPower(base, exponent){
let result = 1;
for(let counter=0; counter<exponent;counter++){
result*=base;
}
return result;
}
input {
width: 3em;
}
Number: <input type="number" id="inputValue"></input><br>
Exponent: <input type="number" id="inputExponent"></input>
<p>
<button onclick="calcFunc()">process</button>
I hope this helps, If the exponent is negative, the result is 1 / (base^exponent). For example: 2^(-4) = 1 / (2^4) = 1 / 2 / 2 / 2 / 2. meaning the number 2 to the power of -4 is: 0.0625 and not 1
Math.abs is important here...
function fetchValue(id){
return document.getElementById(id).value;
}
function calcPower(base, exponent){
if (exponent == 0){
return 1;
}
else if(exponent < 0){
exponent = Math.abs(exponent);
return (1 / calcPower(base, exponent));
}
else if(exponent > 0){
return base * (calcPower(base,exponent - 1));
}
};
I am currently learning JS and when I do some practice, I find some issues I am unclear on data type in Javascript. I understand that JS do NOT require specific type indication, it will automatically do the type conversion whenever possible. However, I suffer one problem when I do NOT do type conversion which is as follows:
var sum = 0;
function totalSum (a) {
if (a == 0) {
return sum;
}
else {
sum += a;
return totalSum(--a);
}
}
var i = prompt("Give me an integer");
// var num = parseInt(i);
alert("Total sum from 1 to " + i + " = " + totalSum(i));
// alert("Total sum from 1 to " + i + " = " + totalSum(num));
I notice that the code works perfectly if I change the data type from string to int using parseInt function, just as the comment in the code does. BUT when I do NOT do the type conversion, things are getting strange, and I get a final result of 054321, if I input the prompt value as 5. AND in a similar way, input of 3, gets 0321 and so on.
Why is it the case? Can someone explain to me why the totalSum will be such a number? Isn't javascript will automatically helps me to turn it into integer, in order for it to work in the function, totalSum?
The sample code can also be viewed in http://jsfiddle.net/hphchan/66ghktd2/.
Thanks.
I will try to decompose what's happening in the totalSum method.
First the method totalSum is called with a string as parameter, like doing totalSum("5");
Then sum += a; (sum = 0 + "5" : sum = "05") (note that sum become a string now)
then return totalSum(--a);, --a is converting the value of a to a number and decrement it's value. so like calling return totalSum(4);
Then sum += a (sum = "05" + 4 : sum = "054") ...
See the documentation of window.prompt: (emphasis mine)
result is a string containing the text entered by the user, or the value null.
I have below javascript code with loop but I can't get the average of it. I'm not sure what's wrong with my code. It's like the first prompt you will input a number and it will loop and you input numbers like how much you entered and you will get the sum of all the numbers and get the average of it after it's done. Here's the code that I have.
function show_prompt()
{
var n=prompt("Input a number: ", "Number here");
if (n==n)
{
var i=1;
do
{
var g=prompt("Input grade: " );
var grade=parseInt(g);
var total=grade+grade;
i++;
}
while(i<=n);
}
var average=(total)/n;
document.write("Average is: " +average);
}
Thanks in advance!
You are overriding your "total" variable in each interval with double the grade value.
var grade=parseInt(g);
var total=grade+grade;
should be changed to
var grade=parseInt(g);
total=total+grade;
Also, you need to initialize the "total" variable in the beginning of your code.
See demo code: http://jsfiddle.net/56ouvan3/1/
I would also recommend some input validation (such as checking that the number of grades requested to average are greater than 0, all grades are positive, etc.)
I think you wanted to accomplish something like that:
http://jsfiddle.net/3L8dL228/1/
Just replace the console.log with your own document.write.
Now, despite I totally hate using prompts and I'm not very used to them, here are you what I think you're missing in your script:
CONTROL: your "n" and "g" variables HAS to be an integers, so force the user to insert an integer.
Variables declaration: you're declaring total every single time you loop, therefore you're not storing anything at all.
To fix these, the very first piece of your code becomes this:
var n = prompt("Input a number: ", "Number here");
while (!parseInt(n) )
{
n=prompt("Input a number: ", "Number here");
}
In this way, you're asking the user to give you a NUMBER, but the script won't procede until it will effectively be able to parse an integer value.
Therefore, inputs like "hey", "hello", "foo", "bar", "baz" won't be accepted.
The second part of your code then becomes this one:
var i=1;
var total = 0;
do
{
var g = prompt("Input grade: " );
while (!parseInt(g)) {
g = prompt("Input grade: " );
}
var grade = parseInt(g);
total += grade;
i++;
}
while(i<=n);
var average=(total)/n;
console.log("Average is: " +average);
and console.log needs to be document.write in your case, but for testing purposes and because jsfiddle (of course) doesn't allow document.write you need to check your console to see the correct value.
What changes from your script to this one is that we are declaring total as a global variable, not as a local variable inside the do loop that will be reset each time you loop.
Next, we're using the same logic as the first prompt for the second one, because you want, again, an integer value, not a possible string like "hey".
After that, we're ADDING that value to the total variable, by not redeclaring it.
Finally, after the loop, we're dividing that global variable total by the global variable n, getting the average.
Try below code to get the average of the entered number.
numGrades = prompt("Enter number of grades to be entered: ");
//number of grades to be entered LOOP
for (index = 1; index <= numGrades; index++) {
numberGrades = prompt("Enter Grade " + index);
}
//Calculation
gradePointAverage = numberGrades / numGrades;
document.write("Your GPA is " + gradePointAverage );
Good morning / Afternoon / evening :).
i have two integers that i want to turn them floats, with 4 decimal numbers to use them on GPS coordinates:
var z = y.toFixed(4);
var p = x.toFixed(4);
But there are a situation that is bugging me, that is the sum between these 'z' and 'p':
var t = z + p;
After this instruction, i want to print the result on the screen with some common functions like:
document.write(z); document.write("<br />");
document.write(t);
document.write("<br />");
document.write("<br />");
The result that i get is:
0.0000
0.0000300.0000
1.0000
1.0000300.0000
2.0000
2.0000300.0000
But what i really want is:
300.0000
301.0000
302.0000
How can i sum 'z' and 'p', after all? :S
Noob question, i know :S.
Kind regards,
Sam
That's because .toFixed() returns a String object rather than a Number, so the + operator performs concatenation.
Instead you should perform the addition of the actual numbers first and then perform .toFixed() to "round" the result for display.
var t = (x + y).toFixed(4);
document.write(t);
I think what you want is :
var t = x + y;
var p = t.toFixed(4);
document.write(p);
try this
var t = (x + y).toFixed(4);
fiddle here
The JavaScript method toFixed converts your number into a string. Thus, when you perform operation z + p it actually is string concantenation and not addition of numbers. You may first add your numbers and afterwards apply toFixed.
toFixed() returns a string, which means you are concating string when you use var t = z + p. You need to first sum your coordinates and then call toFixed().
How much is p? Are you concatenating strings?
Try with var t = parseFloat(z) + parseFloat(p);
While I do know that the following question is stupid simple, it is related to a specific situation that I have been unable to find through Google. The following code is in Javascript.
Suppose there is a variable
x = x + 1;
I can see from a tutorial that this is supposed to work. However, how are we supposed to use this variable in a calculation?
I have tried with the following codes
var name = name + 1;
alert(name);
The above outputs "NaN"; whatever that is...
var name = name + 1;
name = 2;
alert(name);
The above outputs 2 which is simply overriding the original variable.
name = prompt("input any number");
var name = name + 1
alert(name);
The above outputs the input provided + 1 as a string, i.e. 01 where the input is "0" without quotes.
I remember from a ruby lesson that we use .to_i in order to convert a string to an integer. How do we go about doing this in Javascript?
var name = name + 1;
The above code declares a new variable called name which contains whatever name contained before, plus 1. Since name only just came into existence, it doesn't have a numeric value ("Not A Number", or NaN). Adding 1 to NaN gives NaN.
+ means different things in different contexts. If the two operands are numbers, then it does addition. If one operand is a String, it does String concatenation, so
var x = "2"; // x is the String "2"
alert(x+2); // "22"
var x = 2; // x is the number 2
alert(x+2); // 4
If you want to convert a String to a number, you can do
if (x) x = parseInt(x, 10);
where the second argument is the radix (i.e. the base of the number system), and you should use it. If someone entered 02 for example, the radix prevents javascript from treating that as an octal (or other) number.
Of course, you always need to make sure your variables are defined before you use them. I bet your NaN result is coming from the variable not being defined.
Your issue is that you never initialize name. For example:
var name = 0;
alert(name); // Name is 0
name = name + 1;
alert(name); // Name is 1
If you don't initialize it, it will give you NaN: Not a Number.
To turn a string into a number, use parseInt or parseFloat:
var name = prompt("input any number"); // I input 3
name = parseFloat(name);
name = name + 1;
alert(name); // Name is 4
Use parseInt to convert a string to a number.
The line x = x + 1 says "take the existing value of x, add one to it, and store the resulting value back in x again".
The line var name = name + 1 is meaningless since name does not have an existing value when the statement is executed. It is the same as saying undefined + 1 which is NaN (Not a Number).
Here are some examples of how the + operator works in JavaScript:
1 + 2 // number + number is a number -> 3
"1" + 2 // string + anything is a string => "12"
1 + "2" // anything + string is a string => "12"
"1" + "2" // string + string is a string => "12"
NaN means "not a number". Since name has no value when it is first declared, saying "var name = name + 1" doesn't have a numerical meaning, since name is in the process of being declared when used for the first time.
In the second example, name is determined to be a string. Javascript isn't as sensitive to types as some other languages, so it uses + as a concatenation operator instead of a numerical one, since it makes more sense in context,