Program works but calculation doesn't work for input numbers


#1

Hey guys ! :slight_smile:

So the program works, but I've got this problem: the user inputs several sleeping hours, which are (I guess) converted to numbers but these don't want to sum up between them.

Here's the screenshot:

As you can see I have entered "1", "2", "3", and so on for the sleeping hours during the week and "8" for the ideal sleeping hours.

The amount of ideal sleeping hours is right because 8 * 7 = 56.

But the input numbers are just displayed next to each other... How do I "force" them to be summed up?

Thanks!


#2

    parseInt(hours)
    return hours

hours is still a string. '1' + '2' => 12


#3

I guessed it. But I tried with Number(hours) and it didn't transform it to a string neither...

Just copy/paste the code you will see by yourself...

So... How do I transform it to a number ?


#4

Combine the two line so there is an assignment.

return parseInt(hours)

#5

Your problem was that function getSleepHours() returns prompt result, not parsed value:

var hours = prompt(); // you have string result
parseInt(hours); // hours converted to number, but it is not return value for function
return hours; // still returns string hours

So, the best solution posted by @mtf:

var hours = prompt(); // you have string result
return parseInt(hours); // function returns converted value

or assign convertation to new value:

var hours = prompt(); 
var result = parseInt(hours);
return result;

#6

Wow ok ! This was tricky haha.

I mean yeah it is logical, on one line I tell the computer to convert it to a number, that's all.

On the other line I tell it to return the value contained in "hours", which is a string...

Thank you guys ! :smiley:


#7

A post was split to a new topic: What does parseInt mean or do?


#8