Search code examples
phpbcmath

Bcmath adding decimal places randomly


I have a PHP function I got from the web that uses bcmath functions:

function SteamID64to32($steamId64) {
    $iServer = "1";
    if(bcmod($steamId64, "2") == "0") {
        $iServer = "0";
    }
    $steamId64 = bcsub($steamId64,$iServer);
    if(bccomp("76561197960265728",$steamId64) == -1) {
        $steamId64 = bcsub($steamId64,"76561197960265728");
    }
    $steamId64 = bcdiv($steamId64, "2");
    return ("STEAM_0:" . $iServer . ":" . $steamId64);
}

For any valid input the function will at random times add ".0000000000" to the output.

Ex:

$input = 76561198014791430;
SteamID64to32($input);

//result for each run
STEAM_0:0:27262851
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851
STEAM_0:0:27262851
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851.0000000000

This was tested on 2 different nginx servers running php-fpm. Please help me understand what is wrong here. Thanks


Solution

  • The answer provided by JD doesn't account for all possible STEAM_ ID types, namely, anything that is in the STEAM_0:1 range. This block of code will:

    <?php
    
    function Steam64ToSteam32($Steam64ID)
    {
        $offset = $Steam64ID - 76561197960265728;
        $id = ($offset / 2);
        if($offset % 2 != 0)
        {
            $Steam32ID = 'STEAM_0:1:' . bcsub($id, '0.5');
        }
        else
        {
            $Steam32ID = "STEAM_0:0:" . $id;
        }
        return $Steam32ID;
    }
    
    echo Steam64ToSteam32(76561197960435530);
    echo "<br/>";
    echo Steam64ToSteam32(76561197990323733);
    echo "<br/>";
    echo Steam64ToSteam32(76561198014791430);
    ?>
    

    This outputs

    STEAM_0:0:84901
    STEAM_0:1:15029002
    STEAM_0:0:27262851
    

    The first one is for a Valve employee and someone who's had a Steam account since 2003 (hence the low ID), the second is a random profile I found on VACBanned which had an ID in the STEAM_0:1 range. The third is the ID you provided in your sample code.