Javascript parseInt() function

프로그램 이야기 | 2007/08/05 17:14 | 낭만곰팅
알다시피 자바스크립트에서 문자열로된 숫자를 정수로 바꿀 때 흔히 쓰는 자바스크립트의 전역함수(Global Function)이다.
근데 이게 좀 특이하게 동작하는 구석이 있다.
0으로 시작하는 문자열을 경우(0x 또는 0X로 시작하하지 않고) 브라우져는 8진수(IE,FF)또는 10진수(Opera)로 해석한다.

parseInt함수의 syntax는 다음과 같다.
parseInt(string[, radix])
  • string: 정수로 바꿀 대상 문자열
  • radix: 문자열을 바꿀때 사용할 기수(基數, base), 2이상 36이하인 정수 - optional
  • returns: 문자열을 parsing한 정수값(10진수) 또는  NaN
MDC Javascript 레퍼런스를 보면 radix가 0 이거나 생략되었을때 '0'으로 시작되는 문자열의 경우에 radix를 8이라고 되어있다.

If the radix is not specified or is specified as 0, JavaScript assumes the following:

  • If the input string begins with "0x", the radix is 16 (hexadecimal).
  • If the input string begins with "0", the radix is eight (octal). This feature is deprecated.
  • If the input string begins with any other value, the radix is 10 (decimal).
그런데 ECMAScript 스펙을 보면 얘기가 좀 다르다.
radix가 없고 0으로 시작하는 문자열(but  not 0x or 0X)을 8진수 또는 10진수로 구현하는것을 허용한다고 되어있다.
이렇다 보니 IE나 Firefox8진수로 반환을 하고 Opera의 경우에는 10진수로 반환을 한다.
사용자 삽입 이미지

이왕이면 그냥 10진수 하나로 정했으면 좋았을 것을..
스펙의 마지막 부분에 10진수로 반환하는것을 권장한다는 말이 있음에도 불구하고 브라우져들은 서로 다른 구현을 채택한듯 하다.
NOTE
parseInt may interpret only a leading portion of the string as an integer value; it ignores any
characters that cannot be interpreted as part of the notation of an integer, and no indication is given
that any such characters were ignored.
When radix is 0 or undefined and the string's number begins with a 0 digit not followed by an x or X,
then the implementation may, at its discretion, interpret the number either as being octal or as being
decimal. Implementations are encouraged to interpret numbers in this case as being decimal.

- ECMA-262 에서 발췌

사실 이것 때문에 07-08-07 이런거 파싱해서 달력을 만들어야 하는데 자꾸 다른 값이 나와서, widget만들면서 삽질좀 했다.
가능하면 parsetInt함수를 사용할 때에는 radix를 가능하면 명시하는 습관을 들이는 것이 좋을 듯하다.

더 자세한 내용은 아래 내용을 참조하자.
2007/08/05 17:14 2007/08/05 17:14

트랙백을 보내세요

트랙백 주소 :: http://www.hijava.net/trackback/38

댓글을 달아 주세요

[로그인][오픈아이디란?]
비밀글 (Serect)
댓글 달기 (Submit)