1

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.

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>");

Why the sum is not a number?

4
  • Possible duplicate of Javascript function to add two numbers not working right Commented Sep 19, 2017 at 12:18
  • 3
    var sum = sum(value1, value3); and apart from that, some other mistakes, parseFloat is wrong too as you're retrieving a string. Commented Sep 19, 2017 at 12:18
  • @AKA: You don't have to notify the OP with a comment that you posted an answer. The same notification system also alerts them of answers in the first place. Commented Sep 19, 2017 at 12:29
  • Such a question is the basis of the jQuery meme. (Original question (now deleted - only visible to users with more than 10,000 reputation points).) Commented Aug 20, 2019 at 20:50

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

don't forget to remove the debugger line
Thanks @assembler for noticing that.
Should also be noted that you don't need to parseFloat again inside sum1 as you assign a parsed float already to value1 and value3.
Thaks @Adriani6 i included your comment in the answer. Thanks for improving
I appreciate that pick @kevinSpaceyIsKeyserSöze
1

Although a bit dirty, this works:

var amount = 58.02;
var total = '&pound;' + (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 = '&pound;' + (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: &pound;' + 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: &pound;' + (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!

Comments

0

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.

Comments

0

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).

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.