<?php

function formatFloat($value)
{
    $phpPrecision = 14;

    if ($value == 0.0)  return '0.0';
    
    if (log10(abs($value)) < $phpPrecision) {
    
        $decimalDigits = max(
            ($phpPrecision - 1) - floor(log10(abs($value))),
            0
        );

        $formatted = number_format($value, $decimalDigits);

        // Trim excess 0's
        $formatted = preg_replace('/(\.[0-9]+?)0*$/', '$1', $formatted);

        return $formatted;

    }
    
    $formattedWithoutCommas = number_format($value, 0, '.', '');
    
    $sign = (strpos($formattedWithoutCommas, '-') === 0) ? '-' : '';

    // Extract the unsigned integer part of the number
    preg_match('/^-?(\d+)(\.\d+)?$/', $formattedWithoutCommas, $components);
    $integerPart = $components[1];

    // Split into significant and insignificant digits
    $significantDigits   = substr($integerPart, 0, $phpPrecision);
    $insignificantDigits = substr($integerPart, $phpPrecision);

    // Round the significant digits (using the insignificant digits)
    $fractionForRounding = (float) ('0.' . $insignificantDigits);
    $rounding            = (int) round($fractionForRounding);  // Either 0 or 1
    $rounded             = $significantDigits + $rounding;
    
    // Pad on the right with zeros
    $formattingString = '%0-' . strlen($integerPart) . 's';
    $formatted        = sprintf($formattingString, $rounded);
    
    // Insert a comma between every group of thousands
    $formattedWithCommas = strrev(
        rtrim(
            chunk_split(
                strrev($formatted), 3, ','
            ),
            ','
        )
    );

    return $sign . $formattedWithCommas;
}

$randomFloats = array();

for ($i = 0; $i < 500; $i++) {
    $float  = mt_rand() / mt_getrandmax();
    $float  = round($float, mt_rand(0, 15));
    $float *= pow(10, mt_rand(-25, 25));
    if (mt_rand() / mt_getrandmax() > 0.5) {
        $float *= -1.0;
    }
    $randomFloats[] = $float;
}

sort($randomFloats);

foreach ($randomFloats as $float) {
    echo sprintf('%20s', $float) . " --> " . formatFloat($float) . "\n";
}