3

I am writing a basic function to complete exercism.io's Space Age(easy) activity. The function I've written returns the correct number but as a string, can someone please advise why?

I know this is probably a simple answer, but I'm lost even after running through the debugger tool and searching stack overflow questions.

Please don't provide a solution to the exercise , as I'd like to figure that out on my own.

I have read similar titled questions on stack overflow, such as: Number function returning string

var age = (planet, seconds) => {

    var orbitalPeriod;

    const solarsystem = {
        earth : 1,
        mercury : 0.2408467,
        venus : 0.61519726,
        mars : 1.8808158, 
        jupiter : 11.862615, 
        saturn : 29.447498, 
        uranus : 84.016846,
        neptune : 164.79132
    }
    orbitalPeriod = solarsystem[planet];

    return (seconds / 31557600 / orbitalPeriod).toFixed(2);
}

age('mercury',2134835688); 

// returns "280.88"

I have also tried using Number and parseFloat on the orbitalPeriod variable and return value like:

    orbitalPeriod = Number.parseFloat(solarsystem[planet]);

    return Number.parseFloat(seconds / 31557600 / orbitalPeriod).toFixed(2);
sdsm
  • 55
  • 6

2 Answers2

0

Use parseFloat after toFixed.

Note: There is not need to put Number before parseInt or parseFloat they are on window object.

return Number.parseFloat((seconds / 31557600 / orbitalPeriod).toFixed(2));

Or use Unary Plus +.

return +((seconds / 31557600 / orbitalPeriod).toFixed(2));
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
-1

You have to use parseFloat for the entire output. as in your question you used .toFixed(2) which will return string. you need to add parseFloat for the entire result.

var age = (planet, seconds) => {

    var orbitalPeriod;

    const solarsystem = {
        earth : 1,
        mercury : 0.2408467,
        venus : 0.61519726,
        mars : 1.8808158, 
        jupiter : 11.862615, 
        saturn : 29.447498, 
        uranus : 84.016846,
        neptune : 164.79132
    }
    orbitalPeriod = solarsystem[planet];

    return parseFloat((seconds / 31557600 / orbitalPeriod).toFixed(2));
}

var ageVal = age('mercury',2134835688);
console.log(ageVal, typeof(ageVal));
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59
  • 1
    My guess is because OP says "*Please don't provide a solution to the exercise , as I'd like to figure that out on my own.*" – VLAZ May 10 '19 at 05:42
  • 1
    Thanks for the quick response. I see, I was using the toFixed method incorrectly. – sdsm May 10 '19 at 06:02