How to replace a digit in a floating-point number by index with PHP

1 Answer

0 votes
function replaceFloatDigit(float $number, int $position, string $newDigit): float {
    // Validate that newDigit is indeed a single digit
    if ($newDigit < '0' || $newDigit > '9') {
        throw new InvalidArgumentException("Replacement must be a digit (0-9).");
    }

    // Convert number to string with fixed precision (10 decimal places)
    $strNum = number_format($number, 10, '.', '');

    // Validate position
    if ($position < 0 || $position >= strlen($strNum)) {
        throw new OutOfRangeException("Position is out of range for the number string.");
    }

    // Ensure position points to a digit
    if ($strNum[$position] === '.' || $strNum[$position] === '-') {
        throw new InvalidArgumentException("Position points to a non-digit character.");
    }

    // Replace digit
    $strNum[$position] = $newDigit;

    // Convert back to float
    return (float)$strNum;
}

try {
    $num = 89710.291;
    $pos = 2;          // 0-based index
    $newDigit = '8';

    $result = replaceFloatDigit($num, $pos, $newDigit);
    printf("Modified number: %.3f\n", $result);
} catch (Exception $e) {
    fwrite(STDERR, "Error: " . $e->getMessage() . PHP_EOL);
}

 
 
/*
run:
 
Modified number: 89810.291
 
*/

 



answered Nov 17, 2025 by avibootz
...