locutusjs / locutus

Bringing stdlibs of other programming languages to JavaScript for educational purposes

Home Page:https://locutus.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug in php intval function with > 32bits values passed as Number

mikestp27 opened this issue · comments

There is a problem with php intval when the value passed is a Number over 32 bits. It works fine if the value is a String with a value over 32 bits.
The problem is caused by the bitwise operation mixedVar | 0 that is returned in the number case.
Bitwise operations are limited to 32 bits although javascript numbers can be bigger (maybe not 64 bits yet; but at least 53 bits)... https://stackoverflow.com/a/14200122/9471990

Why is mixedVar or'ed | with 0 ?

Here's a test case. Let's use the hex value 0x200000001 which is 34 bits and represented as 8589934593 in decimal:
intval("8589934593") returns 8589934593 OK
intval(8589934593) return 1 !!!!!!

Here's the intval code again:

 var tmp
 var type = typeof mixedVar
 if (type === 'boolean') {
    return +mixedVar
  } else if (type === 'string') {
    tmp = parseInt(mixedVar, base || 10)
    return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp
  } else if (type === 'number' && isFinite(mixedVar)) {
    return mixedVar | 0
  } else {
    return 0
 }

I fail to see the reason for the | 0...

I've pushed a change to the intval. The | 0 was used to remove the fractional part of the number. Replaced it with Math.ceil and Math.floor calls. Didn't use Math.trunc to support Internet Explorer.