declare(strict_types=1);
/**
* Returns the Nth digit after the decimal point.
*
* Examples:
* getNthDecimalDigit(123.456789, 1) => 4
* getNthDecimalDigit(123.456789, 2) => 5
* getNthDecimalDigit(123.456789, 3) => 6
*
* @param float $value The number to inspect.
* @param int $position The digit position after the decimal point (1-based).
*
* @return int The requested digit, or 0 if it does not exist.
*
* @throws InvalidArgumentException If position is less than 1.
*/
function getNthDecimalDigit(float $value, int $position): int
{
if ($position < 1) {
throw new InvalidArgumentException(
'Position must be a positive integer.'
);
}
// Convert to positive value.
$value = abs($value);
/*
* Convert the number to a string with a fixed number
* of decimal places.
*/
$numberString = sprintf('%.15f', $value);
// Find the decimal point.
$decimalPos = strpos($numberString, '.');
if ($decimalPos === false) {
return 0;
}
// Calculate the index of the requested digit.
$digitIndex = $decimalPos + $position;
// Return 0 if the digit does not exist.
if (!isset($numberString[$digitIndex])) {
return 0;
}
return (int)$numberString[$digitIndex];
}
// -----------------------------------------------------------------------------
// Usage Examples
// -----------------------------------------------------------------------------
$number = 123.456789;
echo "Number: {$number}\n\n";
for ($i = 1; $i <= 6; $i++) {
echo "{$i} digit after decimal = "
. getNthDecimalDigit($number, $i)
. PHP_EOL;
}
echo PHP_EOL;
echo "Additional Examples" . PHP_EOL;
echo "-------------------" . PHP_EOL;
echo "123.456789, position 4 -> "
. getNthDecimalDigit(123.456789, 4)
. PHP_EOL;
echo "-98.7654, position 2 -> "
. getNthDecimalDigit(-98.7654, 2)
. PHP_EOL;
echo "1.2, position 5 -> "
. getNthDecimalDigit(1.2, 5)
. PHP_EOL;
/*
run:
Number: 123.456789
1 digit after decimal = 4
2 digit after decimal = 5
3 digit after decimal = 6
4 digit after decimal = 7
5 digit after decimal = 8
6 digit after decimal = 9
Additional Examples
-------------------
123.456789, position 4 -> 7
-98.7654, position 2 -> 6
1.2, position 5 -> 0
*/