PRB: Parseint Returns 0 for Some Strings with Leading ZerosID: Q191434
|
When a string value that contains leading zeros is passed to the parseInt() JScript function, parseInt will return 0 for "08" and "09".
In JavaScript placing a leading 0 in front of a number designates that number as octal. In octal, there is no 08 or 09. Therefore, these numbers are interpreted as 0.
You must remove the leading zeros before calling parseInt. Here is the code for the workaround:
function parseVal(val)
{
while (val.charAt(0) == '0')
val = val.substring(1, val.length);
return val;
}
This behavior is by design.
<HTML>
<HEAD>
<TITLE>Problem with parseInt</TITLE>
</HEAD>
<BODY>
<INPUT TYPE=TEXT name="TXT1">
<SCRIPT FOR="TXT1" EVENT=onchange>
var val = parseInt(TXT1.value);
alert(val);
</SCRIPT>
</BODY>
</HTML>
The following JScript code demonstrates the workaround for this problem.
<HTML>
<HEAD>
<TITLE>THEAD</TITLE>
<SCRIPT LANGUAGE="JScript">
function parseVal(val)
{
while (val.charAt(0) == '0')
val = val.substring(1, val.length);
return val;
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT TYPE=TEXT name="TXT1">
<SCRIPT FOR="TXT1" EVENT=onchange>
var val = parseVal(TXT1.value);
alert(val);
</SCRIPT>
</BODY>
</HTML>
Additional query words:
Keywords : kbIE400 kbIE401 kbJScript300 kbScript kbIE401sp1 kbIE500
Version : WINDOWS:3.0,4.0,4.01,4.01 SP1,5.0
Platform : WINDOWS
Issue type : kbprb
Last Reviewed: July 12, 1999