0

First, I'm sorry I can't speak English well.

I have some problems studying JS. I want to return true if the string is a Number.

If string is "0x10", "0b10", "9843" it work well (all return true). And string like "a463" return false well.

But, when the string is a string with an exponent like "1e43"... it doesn't work well. (it's return false) I want to return true when string with exponent.

if (isNaN(s - 0)) {
  return false;
} else {
  return true;
}

I think have a problem with if().

So, How can I get return true, when the string is with exponent, like "1e22", "13e7"?

lejlun
  • 4,140
  • 2
  • 15
  • 31
Bam
  • 1
  • 1
  • 1
    `"34.12e5"-0 -> 3412000` are you sure your impl isn't working for that exponent notation? – windowsill Oct 29 '21 at 07:12
  • You solution should work because string-to-number cast via `s - 0` or `+s` supports exponential numbers. – Xeelley Oct 29 '21 at 07:29
  • keep in mind this returns 'true' for space characters `' '`. A lot of discussion here: [Check whether variable is number or string in JavaScript](https://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript) – pilchard Oct 29 '21 at 12:42
  • Why are you redefining the grammar for numbers such that you are including exotic things like hex strings (`0xff`) and binary strings (`0b11111111`) but selectively removing just decimals with exponent parts (`2.55e2` or `255e0`)? Do you also want to permit explicit octal strings (`0o377`) and legacy octal strings (`0377`)? What about BigIntegers (`255n`) and what about strings like `Infinity` or `Nan`? _What do you have against exponent notation?_ – Wyck Oct 30 '21 at 04:40

0 Answers0