parseInt returns wrong value on very small numbers




16 years ago
16 years ago


(Reporter: chrsen, Assigned: rogerl)



Firefox Tracking Flags

(Not tracked)





16 years ago
User-Agent:       Mozilla/5.0 (X11; U; Linux i686; da-DK; rv:1.4b) Gecko/20030514
Build Identifier: Mozilla/5.0 (X11; U; Linux i686; da-DK; rv:1.4b) Gecko/20030514

if you have a small number such as 2.40000003423423e-8 parseInt returns 2
instead of 0 as I would have expected. the above number is javascripts internal
representaion of the small number. I belive that parseInt treats it as a string
rather than a number.

Reproducible: Always

Steps to Reproduce:

Expected Results:  
returned 0
> I belive that parseInt treats it as a string

That's the definition of parseInt.  See
section  In particular, the function definition:

   parseInt (string , radix)

and the description of how the function works:

  When the parseInt function is called, the following steps are taken: 
    1. Call ToString(string). 
    2. Let S be a newly created substring of Result(1) consisting of the first
       character that is not a StrWhiteSpaceChar and all characters following
       that character. (In other words, remove leading white space.) 
    3. Let sign be 1.
    ... and so on.

The key part here is step 1.

It sounds like you are looking for Math.round(), not parseInt()....

Comment 2

16 years ago
See also

"parseInt  parses its first argument, the string str, and attempts to return an
integer of the specified radix (base), indicated by the second, optional
argument, radix. For example, a radix of ten indicates to convert to a decimal
number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the
letters of the alphabet indicate numerals greater than nine. For example, for
hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix,
it ignores it and all succeeding characters and returns the integer value parsed
up to that point. If the first character cannot be converted to a number in the
specified radix, it returns "NaN." The parseInt function truncates the string to
integer values."

So parseInt stops processing at the decimal point, and returns '2'.  Marking
this as invalid.
Last Resolved: 16 years ago
Resolution: --- → INVALID

Comment 3

16 years ago
Marking Verified. 

Christian: thank you for this report. Note that JavaScript is a 
language that does implicit type conversion. For example, the 
alert() function takes a string argument, but if you do 


you don't get a JavaScript error; the alert comes up successfully.
That's because JavaScript implicitly converts 2.40000003423423e-8
to the string "2.40000003423423e-8" for you.

The same is true of parseInt(). It takes a string parameter in its
first argument. So 2.40000003423423e-8 is implicitly converted to 
"2.40000003423423e-8", and parseInt() of that is 2.
You need to log in before you can comment on or make changes to this bug.