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!!!
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 .
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 .
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.
The parseFloat function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or NaN .
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))
This would satisfy all your tests:
function func (str) {
var int = parseInt(str, 10);
return str == str.trim() && str == int ? int : NaN
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With