Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to get the Nth digit after the decimal point of a floating-point number in PHP

1 Answer

0 votes
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

*/

 



answered 21 hours ago by avibootz

Related questions

...