-1

This is my code:

function convertFahrToCelsius(temp) {
  if(typeof(temp) === "number" || typeof(temp) === "string"){
    return ((Number(temp) - 32) * 5/9).toFixed(4);
  } else {
    return `${temp} is not a valid number but a/an ${typeof(temp)}`;
  }
}

console.log(convertFahrToCelsius(0));
console.log(convertFahrToCelsius("0") );
console.log(convertFahrToCelsius([1,2,3]));
console.log(convertFahrToCelsius({temp: 0}));

This should be the output:

- convertFahrToCelsius(0) should return `-17.7778`
- convertFahrToCelsius("0") should return `-17.7778`
- convertFahrToCelsius([1,2,3]) should return `[1,2,3] is not a valid number but a/an array.`
- convertFahrToCelsius({temp: 0}) should return `{temp: 0} is not a valid number but a/an object.`

This is my ouput:

- convertFahrToCelsius(0);: -17.7778
- convertFahrToCelsius("0");:-17.7778
- convertFahrToCelsius([1,2,3]);:1,2,3 is not a valid number but a/an object
- convertFahrToCelsius({temp: 0});:[object Object] is not a valid number but a/an object

I need the last two outputs to be the same as it should be.

svg-code
  • 1
  • 1
  • I don't get it, should `convertFahrToCelsius([1,2,3])` return a string that says `[1,2,3] is not a valid number but a/an array.`? – First dev May 16 '21 at 19:13
  • Does this answer your question? [Converting an object to a string](https://stackoverflow.com/questions/5612787/converting-an-object-to-a-string) – Ivar May 16 '21 at 19:15
  • or you mean `convertFahrToCelsius({temp: 0});` it should return `{temp: 0} is not a valid number but a/an object.` instead of `[object Object] is not a valid number but a/an object` – First dev May 16 '21 at 19:16
  • @SubodhW, thank you, JSON.stringify() did the magic. – svg-code May 17 '21 at 10:31
  • @svg-code, Please vote my answer as Useful. – Subodh Wasankar May 25 '21 at 21:41

1 Answers1

-1

Try JSON.stringify()

function convertFahrToCelsius(temp) {
  if(typeof(temp) === "number" || typeof(temp) === "string"){
    return ((Number(temp) - 32) * 5/9).toFixed(4);
  } else {
    return `${JSON.stringify(temp)} is not a valid number but a/an ${typeof(temp)}`;
  }
}

console.log(convertFahrToCelsius(0));
console.log(convertFahrToCelsius("0") );
console.log(convertFahrToCelsius([1,2,3]));
console.log(convertFahrToCelsius({temp: 0}));
Subodh Wasankar
  • 309
  • 2
  • 6