The One with the Thoughts of Frans

parseIntHelper()

The results of parseInt() are somewhat inconsistent, so I wrote this to clean it up (also see there). What to do with it? Who knows; it might come in handy someday.

function parseIntHelper(numberString, radix) {
	numberString = (typeof numberString === 'number') ? numberString.toString() : numberString; // I guess we should support number input just like parseInt.
	radix = (typeof radix === 'undefined') ? 10 : radix; // Set radix to 10 if undefined.
	
	numberString = numberString.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // Trim. Taken from http://blog.stevenlevithan.com/archives/faster-trim-javascript
	
	// Check if octal; non-standard but in line with other languages
	if ( numberString.indexOf('0o') === 0 || numberString.indexOf('0O') === 0 ) {
		numberString = numberString.slice(2); // Remove '0o'.
		radix = 8;
	}
	
	// Check if hex
	if ( numberString.indexOf('0x') === 0 || numberString.indexOf('0X') === 0 ) {
		numberString = numberString.slice(2); // Remove '0x'.
		radix = 16;
	}
	
	for (var i=0; i<numberString.length; i++) {
		var nStr = numberString[i];
		if (nStr === '.') {
			continue; // Ignore decimal mark, or rather the radix point. Maybe a check against more than 1 of these?
		}
		var parsed = parseInt(nStr, radix);
		if (isNaN(parsed)) {
			return parsed; // Return NaN if found
		}
	}
	return parseInt(numberString, radix); // Return regular parseInt if there was no shenanigans. Note that we do not support octal numbers prefixed with 0 because it's not in the ECMAScript 5 spec, although we do support the equally non-standard prefixed with 0o. That's because the behavior prefixed with 0 is just too unreliable, while we control what happens with 0o.
}

Leave a Comment

You must be logged in to post a comment.