Search code examples
javascriptstringfunctionnumbersjavascript-objects

expected number, but returning string


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

Solution

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