Sven Rautenberg: parseInt() und intval()

Beitrag lesen

Moin!

tipp doch mal auf das Ergebnis.

javascript:alert(parseInt("0834"))       zum copieren in die Adresszeile

das Ergebnis möchte man bestimmt nicht haben. Also korrigiere das js-Script

Interessant.
Firefox 2.0 und IE 5.5

Opera 9.24:

javascript:alert(parseInt("0834"))      -->    0

-->  834

Damit ist bewiesen, dass man unmöglich mit PHP eine Funktion bauen kann, die sich wie "parseInt" in Javascript verhält, weil es für parseInt in Javascript kein browserübergreifend identisches Verhalten gibt, nach welchem Zahlensystem Strings zu interpretieren sind.

Die Dokumentation von Mozilla sagt dazu:
"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)."

"Deprecated", sprich: "Soll nicht mehr, wird aber noch!"

Opera ist da anscheinend schon weiter.

Wie man hier im Forum nachlesen kann, hat sich in diesem Punkt der ECMA-Standard geändert:

" B.1 Additional Syntax

Past editions of ECMAScript have included additional syntax and semantics for
  specifying octal literals and octal escape sequences. These have been removed
  from this edition of ECMAScript. This non-normative annex presents uniform
  syntax and semantics for octal literals and octal escape sequences for
  compatibility with some older ECMAScript programs."

Der Rest der Zahlen ist selbstverständlich identisch, weil ja definiert ist, wie die Zahlen zu verstehen sind:

javascript:alert(parseInt("0834",10))   -->  834

-->  834

javascript:alert(parseInt("0834",8))    -->    0

-->    0

javascript:alert(parseInt("0834",16))   --> 2100

--> 2100 (ist aber auch nicht überraschend)

javascript:alert(parseInt("834",8))     --> NaN

--> NaN

- Sven Rautenberg

--
"Love your nation - respect the others."