12

Prompt as it is possible to translate a string to number so that only any variant except for the integer produced an error.

func('17') = 17;
func('17.25') = NaN
func(' 17') = NaN
func('17test') = NaN
func('') = NaN
func('1e2') = NaN
func('0x12') = NaN

ParseInt does not work, because it does not work correctly.

ParseInt('17') = 17;
ParseInt('17.25') = 17 // incorrect
ParseInt(' 17') = NaN
ParseInt('17test') = 17 // incorrect
ParseInt('') = NaN
ParseInt('1e2') = 1 // incorrect

And most importantly: for the function to work in IE, Chrome and other browsers!!!

1
  • Number() will get you close, but do you want to discard decimal places or do you really want to reject them as NaN? Commented Apr 14, 2017 at 19:27

2 Answers 2

14

You can use a regular expression and the ternary operator to reject all strings containing non-digits:

function intOrNaN (x) {
  return /^\d+$/.test(x) ? +x : NaN
}

console.log([
  '17', //=> 17
  '17.25', //=> NaN
  ' 17', //=> NaN
  '17test', //=> NaN
  '', //=> NaN
  '1e2', //=> NaN
  '0x12' //=> NaN
].map(intOrNaN))

Sign up to request clarification or add additional context in comments.

2 Comments

Why did you add + before x?
@WessamElMahdy The unary + operator casts the value of x to a number (hence strings of digits are reinterpreted as a base-10 numeric literal)
3

This would satisfy all your tests:

function func (str) {
  var int = parseInt(str, 10);
  return str == str.trim() && str == int ? int : NaN
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.