Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse an integer (and *only* an integer) in JavaScript

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!!!

like image 741
Zhihar Avatar asked Apr 14 '17 19:04

Zhihar


People also ask

What is parse int in JavaScript?

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .

What happens if you use parseInt () to convert a string containing decimal value?

parseInt will only parse the leading part of the string that defines a whole number ("int" = "integer" = "whole number"), so it stops at the , . parseFloat will parse a decimal number, but only understands .

Why is parse int used?

The parseInt() function is used to accept the string ,radix parameter and convert it into an integer. The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

What does parseFloat do in JavaScript?

The parseFloat function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or NaN .


2 Answers

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))
like image 198
gyre Avatar answered Oct 21 '22 01:10

gyre


This would satisfy all your tests:

function func (str) {
  var int = parseInt(str, 10);
  return str == str.trim() && str == int ? int : NaN
}
like image 3
Linus Thiel Avatar answered Oct 21 '22 00:10

Linus Thiel